相同for循环和列表理解的不同输出

2024-03-29 11:39:41 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码转换字符串列表示例:

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")]}]

谢谢你的帮助!你知道吗


Tags: nameinid列表forstringbaritems
1条回答
网友
1楼 · 发布于 2024-03-29 11:39:41

我运行过这个代码

row = ["pet:1,car:0", "name:0,bar:2"]
results = [{"id": [tuple(id_string.split(":")) for id_string in id.split(",") if '' not in id_string.split(",")]} for id in row]
print(results)
>>>> [{'id': [('pet', '1'), ('car', '0')]}, {'id': [('name', '0'), ('bar', '2')]}]

现在,我可以在你的代码中看到两个奇怪的东西,它们都包含在你的列表中

for id in rows
  1. rows在未定义中,您使用了row
  2. 不要使用id,因为它在Python中是^{}函数的保留关键字。你知道吗

这可能更合适

results = [{"id": [tuple(id_string.split(":")) for id_string in item.split(",") if '' not in id_string.split(",")]} for item in row]

相关问题 更多 >