如何在python中合并2个2D列表? [英] How to combine 2 2D lists in python?

查看:102
本文介绍了如何在python中合并2个2D列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,我有一个小问题.

I am pretty new to python, and I have a little problem.

我需要像这样组合两个2D列表:

I need to combine two 2D lists like this:

list1= [[some,1],[thing,5]]
list2= [[some,1],[other,1],[thing,5]]

结果应如下所示:

result= [[some,2],[other,1],[thing,10]]

推荐答案

您可以使用 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})

这篇关于如何在python中合并2个2D列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆