python - Python将命名字符串字段转换为元组
问题描述
类似于这个问题:Tuple declaration in Python
我有这个功能:
def get_mouse():
# Get: x:4631 y:506 screen:0 window:63557060
mouse = os.popen( "xdotool getmouselocation" ).read().splitlines()
print mouse
return mouse
当我运行它时,它会打印:
['x:2403 y:368 screen:0 window:60817757']
我可以拆分行并在列表中创建 4 个单独的字段,但是从我看到的 Python 代码示例中,我觉得有更好的方法来做到这一点。我在想像x:=
or之类的东西window:=
。
我不确定如何正确定义这些“命名元组字段”,也不确定如何在后续命令中引用它们?
如果有方便的参考链接,我想阅读有关整个主题的更多信息。
解决方案
尝试
dict(mouse.split(':') for el in mouse
这应该给你一个字典(而不是元组,虽然字典是可变的并且还需要键的哈希性)
{x: 2403, y:368, ...}
也splitlines
可能不需要,因为您只阅读一行。您可以执行以下操作:
mouse = [os.popen( "xdotool getmouselocation" ).read()]
虽然我不知道是什么xdotool getmouselocation
,或者它是否可以返回多行。
推荐阅读
- java - 如何将 ElasticSearch 索引(使用 Logstash 和 MySQL 提供数据)连接到 Java Rest 高级客户端(Spring Boot)
- r - XML 安装似乎失败并且未在 R 上加载
- ruby-on-rails - 即使列为 nil Rspec 也通过验证
- android - 字符串中的自动完成功能未在 android studio (Kotlin) 上显示
- php - 使用 UUID 将权限分配给 spatie/laravel-permission 中的角色时的非法偏移类型
- pandas - 我在 k=f1_score(temp, train_y) 上收到“DataFrame object is not callable”
- c++ - C++ 队列函数调用
- javascript - 用正则表达式替换值
- python - 如何从列表(txt 文件)中读取字符串并将它们打印为整数、字符串和浮点数?
- css - Flexbox 动态布局