我有一个词典列表,我目前的列表理解是分离词典(即创建新的词典,而不是之前的词典)。以下是一些帮助说明问题的示例代码。
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()
,您会注意到我现在有六个词典。我相信我正在尝试做的事情 - 即用一个空格("<br>"
)替换值" "
- 是可能的,但我不知道如何做。
{key: val.method()}
。我唯一没有 尝试的是三元列表理解,因为我可以看到它太长了以至于我永远不会想要它在生产代码中。
有什么见解?我是否可以在不影响字典的初始结构的情况下操纵列表理解中某些词汇的值?
答案 0 :(得分:4)
字典理解正在执行六次,因为您当前的代码与此相当:
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
外部循环将运行三次,因为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'}]
>>>
现在,词典理解只会执行三次:list_of_dicts
中的每个项目一次。
答案 1 :(得分:3)
您正在寻找嵌套理解
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>", " ")
代替?
答案 2 :(得分:2)
在这种情况下,列表理解可能会令人困惑。我建议使用经典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'}]