此代码转换字符串列表示例:
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")]}]
谢谢你的帮助!你知道吗
我运行过这个代码
现在,我可以在你的代码中看到两个奇怪的东西,它们都包含在你的列表中
rows
在未定义中,您使用了row
id
,因为它在Python中是^{这可能更合适
相关问题 更多 >
编程相关推荐