【发布时间】:2018-07-18 15:12:00
【问题描述】:
此代码转换字符串列表示例:
rows = ["pet:1,car:0", "name:0,bar:2"]
到元组列表
result = [("person","1"), ("pet","0")]
我有 for 循环:
for items in rows:
list_of_strings = items.split(",") #Example: ["pet:0", "car:0"]
listchange = []
for id_string in list_of_strings:
listchange.append(tuple(id_string.split(":")))
print(listchange)
这将打印带有元组的列表,其中基本上是所需的输出:
>> [("pet", "1"),("car", "0")]
>> [("name", "0"),("bar", "2")]
我的问题是,当我尝试在以下列表理解中重写相同的 for 循环时,我得到的输出与期望的不同:
results = [
{
"id": [tuple(id_string.split(":"))
for id_string in items.split(",")
if '' not in id_string.split(",")
]
}for items in rows]
这给了我:
>> [{id: [["pet", "1"],["car", "0"]]},
{id: [["name", "0"],["bar", "2"]]}]
我想要的输出应该是这样的:
>> [{id: [("pet", "1"),("car", "0")]},
{id: [("name", "0"),("bar", "2")]}]
感谢您的帮助!
【问题讨论】:
-
运行你的代码对我来说很好(测试了两个版本的 Python)
-
感谢您运行我的代码。您确定它会在第二种情况下为您提供元组列表吗?这对我不起作用...
-
查看我的答案,我包含了输出。
标签: python dictionary for-loop list-comprehension