我有一本字典:
d=[{'court': 4, 'hope': 6},
{'court': 9, 'hope': 27},
{'hope': 5, 'mention': 2, 'life': 10, 'bolster': 1, 'internal': 15, 'level': 1}]
并列出
l=[2, 9, 5]
我只想用相应的字典值划分列表元素。某事,
new_list=[{'court': 2, 'hope': 3},
{'court': 1, 'hope': 3},
{'hope': 1, 'mention': 0.4, 'life': 2, 'bolster': 0.2, 'internal': 3,'level': 0.2}]
我所做的,
new_list=[]
for i in d:
for k,j in i.items():
new={k:j/o for o in l}
new_list.append(new)
它以包含单个元素的列表形式返回:
[{'court': 2},{'hope': 3},
{'court': 1},{'hope': 3},
{'hope': 1},{'mention': 0.4},{'life': 2},{'bolster': 0.2},{'internal': 3},{'level': 0.2}]
最佳答案
通过简单的列表/字典理解:
res = [{k: v/divider for k,v in d[i].items()} for i, divider in enumerate(l)]
print(res)
输出:
[{'court': 2.0, 'hope': 3.0}, {'court': 1.0, 'hope': 3.0}, {'hope': 1.0, 'mention': 0.4, 'life': 2.0, 'bolster': 0.2, 'internal': 3.0, 'level': 0.2}]
或者同zip
函数:
res = [{k: v/divider for k,v in d.items()} for d, divider in zip(d, l)]
关于python - 在python中用字典值划分列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57052469/