python - 将两个列表合并在一起

标签 python merge

我在 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/

相关文章:

python - 如何将函数应用于 python 列表的每个子列表?

python - 小写django查询

git - Msys Git merge 工具命令选项问题

git - 用 develop 覆盖 master

r - 将一个数据帧与日期向量合并

javascript - 如何合并两个脚本并同时触发它们?

python - 如何在HoloViews中获取小部件 "handler"

python - 如何用值 [ODOO 12] 更新 One2many 列表

python - 在 Pandas 中合并具有相同列名但列数不同的两个数据框

python - 相关对象上的 Django 多维查询集