相同的For循环和列表理解的输出延迟

时间:2018-07-18 15:12:01

标签: python dictionary for-loop list-comprehension

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

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我确实运行了这段代码,

create table myTable(identityNo int);
insert into myTable values (1),(3);
VALUES (1),(2),(3),(4) MINUS SELECT identityNo FROM myTable;

1          
-----------
          4
          2

  2 record(s) selected.

现在,我可以在您的代码中看到两个奇怪的东西,它们都包含在列表理解的那一行中,

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')]}]
  1. for id in rows (未定义)中,您使用了rows
  2. 请勿使用row,因为它是Python中id()函数的保留关键字。

这可能更合适

id