我有兩個要組合的集合串列,同時在第一個值匹配時添加第二個集合值。
示例輸入:
listOne = [('a', 1), ('b', 3), ('c', 2), ('d', 5)]
listTwo = [('a', 2), ('b', 1), ('c', 4)]
期望的輸出:
[('a', 3), ('b', 4), ('c', 6), ('d', 5)]
什么是最簡單的方法來做到這一點?
uj5u.com熱心網友回復:
from collections import Counter
result = list((Counter(dict(listOne)) Counter(dict(listTwo))).items())
uj5u.com熱心網友回復:
您可以使用itertools.zip_longest:
from itertools import zip_longest
[((t1[0], t1[1] t2[1]) if t1[0] == t2[1] else t1) if t2 else t1 for t1,t2 in zip_longest(listOne, listTwo)]
輸出:
[('a', 1), ('b', 3), ('c', 2), ('d', 5)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/375598.html
標籤:Python
上一篇:如何為JSON檔案設定條件?
