將兩個列表與 dicts python 相乘

lo7
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}]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章