Skip to main content
 首页 » 编程设计

python:比较这些列表的快速简便方法

2025年05月04日33duanxz

我为此编写了一个函数,但我认为它可能非常低效且过于复杂,所以我想问问是否有一种简单的方法可以做到这一点。

给定两个列表列表...

foo = [['one', 1], ['two', 1], ['three', 1]] 
bar = [['three', 1], ['four', 1], ['five', 1]] 

我需要一个会返回...的函数

final = [['one', 1], ['two', 1], ['three', 2], ['four', 1], ['five', 1]] 

所以它检查第一项是否有任何重叠,将第二项加在一起,然后像上面那样返回最终列表

编辑:

foo/bar[1:] 保证是有序的,但它们可能是这样的......

foo = [['the', 100], ['at', 99], ['for', 32]] 
bar = [['mitochondria', 20], ['at', 10], ['you', 9]] 

换句话说,它们将是相对随机的单词与降序数字配对。

请您参考如下方法:

>>> foo = [['one', 1], ['two', 1], ['three', 1]] 
>>> bar = [['three', 1], ['four', 1], ['five', 1]] 
>>> from collections import Counter 
>>> Counter(dict(foo)) + Counter(dict(bar)) 
Counter({'three': 2, 'four': 1, 'five': 1, 'two': 1, 'one': 1}) 

所以

>>> (Counter(dict(foo)) + Counter(dict(bar))).items() 
[('four', 1), ('five', 1), ('three', 2), ('two', 1), ('one', 1)] 

如果顺序很重要:

>>> from collections import OrderedDict 
>>> counter = (Counter(dict(foo)) + Counter(dict(bar))) 
>>> order = OrderedDict(foo + bar).keys() 
>>> [[k, counter[k]] for k in order] 
[['one', 1], ['two', 1], ['three', 2], ['four', 1], ['five', 1]] 

如果项目被收集到一个列表L

>>> foo = [['one', 1], ['two', 1], ['three', 1]] 
>>> bar = [['three', 1], ['four', 1], ['five', 1]] 
>>> from collections import Counter 
>>> from collections import OrderedDict 
>>> from itertools import chain 
>>> L = [foo, bar] 
>>> counter = Counter() 
>>> for item in L: 
...     counter.update(dict(item)) 
...  
>>> order = OrderedDict(chain.from_iterable(L)) 
>>> [[k, counter[k]] for k in order] 
[['one', 1], ['two', 1], ['three', 2], ['four', 1], ['five', 1]]