【问题标题】:Deferent output for same For loop and list comprehension相同 For 循环和列表理解的不同输出
【发布时间】: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


【解决方案1】:

我确实运行了这段代码,

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中id()函数的保留关键字。

这样可能更合适,

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-20
    • 2019-02-08
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    相关资源
    最近更新 更多