首页 > 解决方案 > 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:=

我不确定如何正确定义这些“命名元组字段”,也不确定如何在后续命令中引用它们?

如果有方便的参考链接,我想阅读有关整个主题的更多信息。

标签: pythontuples

解决方案


尝试

dict(mouse.split(':') for el in mouse

这应该给你一个字典(而不是元组,虽然字典是可变的并且还需要键的哈希性)

{x: 2403, y:368, ...}

splitlines可能不需要,因为您只阅读一行。您可以执行以下操作:

mouse = [os.popen( "xdotool getmouselocation" ).read()]

虽然我不知道是什么xdotool getmouselocation,或者它是否可以返回多行。


推荐阅读