且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python中合并2个2D列表?

更新时间:2023-11-23 20:44:40

您可以使用 collections.Counter :

You can use a collections.Counter:

>>> from collections import Counter
>>>
>>> list1 = [['some',1],['thing',5]]
>>> list2= [['some',1],['other',1],['thing',5]]
>>>
>>> [[k,v] for k,v in (Counter(dict(list1)) + Counter(dict(list2))).items()]
[['thing', 10], ['other', 1], ['some', 2]]

或者如果可以接受元组列表:

Or if a list of tuples is acceptable:

>>> (Counter(dict(list1)) + Counter(dict(list2))).items()
[('thing', 10), ('other', 1), ('some', 2)]

在这里使用元组似乎更有意义.

Using tuples seems to make more sense here.

您应该考虑是否真正需要最终结果作为列表.如果顺序不重要(如您所说的并不重要),那么字典Counter(dict(list1)) + Counter(dict(list2))可能就足够了.

You should consider if you actually need the final result to be a list. If order is not important (as you say it isn't), then the dictionary Counter(dict(list1)) + Counter(dict(list2)) will probably suffice on its own.

>>> Counter(dict(list1)) + Counter(dict(list2))
Counter({'thing': 10, 'some': 2, 'other': 1})