【问题标题】:How to Alter a Dict's Values in a List Comprehension如何在列表理解中更改字典的值
【发布时间】:2014-06-21 22:23:57
【问题描述】:

我有一个字典列表,而我当前的列表理解是分隔字典(即,在以前没有字典的地方创建新字典)。下面是一些示例代码来帮助说明问题。

list_of_dicts = [{"this": "hi<br>", "that":"bye"}, {"this": "bill", "that":"nye"},{"hello":"kitty<br>", "good bye": "to all of that"}]

因此,如您所见,我有一个列表,其len()三个。每个项目都是一个包含两个键和两个值的字典。

这是我的列表理解:

list_of_dicts = [{key: val.replace("<br>", " ")} for dic in list_of_dicts for key, val in dic.items()]

如果你打印这个新行的len(),你会注意到我现在有六个字典。我相信我正在尝试做的事情——即将值中的"&lt;br&gt;" 替换为一个空格(" ")——是可能的,但我不知道怎么做。

到目前为止,我已经尝试了所有我知道的方法来创建字典而不是 {key: val.method()}。我唯一没有尝试过的是三元列表理解,因为我可以看到它太长了,以至于我永远不会在生产代码中使用它。

有什么见解吗?我可以在不影响字典初始结构的情况下在列表理解中操纵某些字典的值吗?

【问题讨论】:

  • 为什么必须是列表理解;为什么不按常规方式遍历列表?
  • 这只是偏好。我可以比嵌套代码更容易阅读列表推导。
  • @jonrsharpe 感谢您的编辑。我的问题总是非常令人困惑。你可能为我赢得了一个非常罕见的支持,所以谢谢:)

标签: python python-2.7 dictionary syntax list-comprehension


【解决方案1】:

字典推导被执行了六次,因为你当前的代码是这样的:

list_of_dicts = [{"this": "hi<br>", "that":"bye"}, {"this": "bill", "that":"nye"},{"hello":"kitty<br>", "good bye": "to all of that"}]
tmp = []

for dic in list_of_dicts:
    for key, val in dic.items():
        tmp.append({key: val.replace("<br>", " ")})

list_of_dicts = tmp

外部循环将运行 3 次,因为 list_of_dicts 包含三个项目。因为list_of_dicts 中的每个字典都有两个项目,所以内部循环将为外部循环的每次迭代运行两次。总之,这一行:

tmp.append({key: val.replace("<br>", " ")})

将被执行六次。


您可以通过简单地将for key, val in dic.items() 子句移动到字典理解中来解决此问题:

>>> list_of_dicts = [{"this": "hi<br>", "that":"bye"}, {"this": "bill", "that":"nye"},{"hello":"kitty<br>", "good bye": "to all of that"}]
>>> [{key: val.replace("<br>", " ") for key, val in dic.items()} for dic in list_of_dicts]
[{'this': 'hi ', 'that': 'bye'}, {'this': 'bill', 'that': 'nye'}, {'hello': 'kitty ', 'good bye': 'to all of that'}]
>>>

现在,字典理解将只执行 3 次:list_of_dicts 中的每个项目一次。

【讨论】:

    【解决方案2】:

    你正在寻找一个嵌套的理解

    list_of_dicts = [dict((key, val.replace("<br>", " "))
                          for key, val in d.iteritems())
                     for d in list_of_dicts]
    

    但是你让事情变得比他们需要的更复杂......更简单的呢:

    for d in list_of dicts:
        for k, v in d.items():
            d[k] = v.replace("<br>", " ")
    

    改为?

    【讨论】:

      【解决方案3】:

      在这种情况下,列表推导可能会令人困惑。我建议使用经典的for 循环:

      来源

      data = [{"this": "hi<br>", "that":"bye"}, {"this": "bill", "that":"nye"},{"hello":"kitty<br>", "good bye": "to all of that"}]
      
      for mydict in data:
          for key,value in mydict.iteritems():
              mydict[key] = value.replace('<br>', '')
      
      print data
      

      输出

      [{'this': 'hi', 'that': 'bye'}, {'this': 'bill', 'that': 'nye'}, {'hello': 'kitty', 'good bye': 'to all of that'}]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多