+-
python – 将两个列表合并在一起
我在 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 – 将两个列表合并在一起 - 乐贴网