我尝试这样:

tmp = "one ; 1 \n two ; 2 \n three ; 3"
choices = [(x.strip(), y.strip())
           for choice in tmp.split("\n")
           for x,y in choice.split(";")
           if choice.find(";") != -1]


我收到的错误消息是:{ValueError} too many values to unpack (expected 2)。我不明白。如果我修改此内容:

>>> choices = [x
               for choice in tmp.split("\n")
               for x in choice.split(";")]
>>> choices
['one ', ' 1 ', ' two ', ' 2 ', ' three ', ' 3']


我看到拆分未正确执行,只是未分配。

基本上我想要这样:

>>> choices = [magical list comp using tmp variable]
>>> choices
[("one", "1"), ("two", "2"), ...etc ]


有人知道吗?!

最佳答案

您可以执行以下操作:

choices = [tuple(map(str.strip, choice.split(";"))) for choice in tmp.split("\n") if choice.find(";")]
print(choices)


输出量

[('one', '1'), ('two', '2'), ('three', '3')]

关于python - Python多列表理解无法正常工作,如何正确执行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58379084/

10-12 21:33