我在 python 中有两个列表:
L1=[[100, 1], [101, 2]]
L2=[[100, 3], [101, 4], [102, 5]]
我想合并它们,所以我得到:
L_merge=[[100, 4], [101, 6], [102, 5]]
重要的是两个列表的大小可能不同。
我试图使用字典,但无法弄明白。我很乐意使用 numpy、pandas 或任何其他工具来实现合并。
最佳答案
你可以使用 collections.Counter
在两个列表上并简单地求和它们:
from collections import Counter
L1 = [[100, 1], [101, 2]]
L2 = [[100, 3], [101, 4], [102, 5]]
L_merge = (Counter(dict(L1)) + Counter(dict(L2))).items()
print(list(L_merge))
# [(100, 4), (101, 6), (102, 5)]
关于python - 将两个列表合并在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40151081/