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'}]
所以我的問題是,如何將這兩個串列相乘?
uj5u.com熱心網友回復:
由于串列已經按相同的順序排序,我建議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}]
uj5u.com熱心網友回復:
您可以先對兩個串列的專案進行排序list1,list2然后將其相乘,如下所示:
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}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/342459.html
標籤:Python
上一篇:如何遍歷字串中的每個字符并將其與其字串中的位置相乘?
下一篇:我如何使用回圈來更改串列中的值
