繁体   English   中英

将两个列表与 dicts python 相乘

[英]Multiply two lists with dicts python

list1 = [{'the': '0.181'}, {'to': '0.115'}, {'a': '0.093'}, {'of': '0.084'}, {'and': '0.078'}]

list2 = [{'the': '1.010'}, {'to': '1.010'}, {'a': '1.000'}, {'of': '1.102'}, {'and': '1.228'}]

结果我试图得到一个这样的新列表:

[{'the': 'list1 *list2'}, {'to': 'list1*list2'}, 
 {'a': 'list1*list2'}, {'of': 'list1*list2'}, {'and': 'list1*list2'}]

所以我的问题是,如何将这两个列表相乘?

由于列表已经按相同的顺序排序,我建议将它们zip并应用您想要的乘法

list1 = [{'the': '0.181'}, {'to': '0.115'}, {'a': '0.093'}, {'of': '0.084'}, {'and': '0.078'}]
list2 = [{'the': '1.010'}, {'to': '1.010'}, {'a': '1.000'}, {'of': '1.102'}, {'and': '1.228'}]

result = []
for pair1, pair2 in zip(list1, list2):
    k1, v1 = list(pair1.items())[0]
    k2, v2 = list(pair2.items())[0]
    if k1 != k2:
        raise Exception(f"Malformed data ({k1},{v1}).({k2},{v2})")
    result.append({k1: float(v1) * float(v2)})

print(result)
# [{'the': 0.18281}, {'to': 0.11615}, {'a': 0.093}, {'of': 0.09256800000000001}, {'and': 0.095784}]

您可以先对list1list2进行排序,然后将两个列表的项目相乘,如下所示:

list2 = sorted(list2, key=lambda x: list(x.keys())[0])
list1 = sorted(list1, key=lambda x: list(x.keys())[0])

res = []
for idx , l in enumerate(list1):
    res.append({list(l.keys())[0] : float(list2[idx].get(*(l.keys()), 1)) * float(*(l.values()))})
    
print(res)

输出:

[{'a': 0.093},
 {'and': 0.095784},
 {'of': 0.09256800000000001},
 {'the': 0.18281},
 {'to': 0.11615}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM