python - 在python中用字典值划分列表元素

标签 python arrays python-3.x dictionary

我有一本字典:

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/

相关文章:

arrays - Matlab 中元胞数组列的重复部分

以优于 O(n^2) 的时间复杂度构造 count 数组

python - 如何在 Numpy 中使用 savetxt 有两个前导空格

python-3.x - 替换数据框中的 0's with 1'

python - 生成非均匀随机数

python - kwargs 的自定义异常 (Python)

python - 给定两个字符串列表,如何将它们转换为字典?

python - 如何抵消 Pandas Pearson 与日期时间索引的相关性

python - 为什么在将参数 tz 指定给 fromtimestamp 方法时,datetime 的子类不是子类的实例?

python - 在 exe 中使用从 DLL 导出的 Python 对象