簡體   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