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

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


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

这是我的清单理解:

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


如果您打印此新行的len(),您会注意到我现在有六个字典。我相信我正在尝试做的事情-即用一个空格("<br>")替换值中的" "-是可能的,但是我不知道如何做。

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

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

最佳答案

由于您当前的代码与此等效,因此字典理解被执行了六次:

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有3个项目。内部循环将为外部循环的每次迭代运行两次,因为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'}]
>>>


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

关于python - 如何在列表理解中更改Dict的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24346391/

10-16 03:16