我试试这个:
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')]
