python:快速简便地比较这些列表?

时间:2015-10-15 03:43:54

标签: python

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

给出两个清单列表......

{{ result.activities[0].attribs["length"] }}

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

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

所以检查第一个术语是否有任何重叠,将第二个术语加在一起,然后返回上面的最终列表

编辑:

保证订购

foo / bar [1:],但它们可能就像这样......

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

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

4 个答案:

答案 0 :(得分:5)

>>> 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]]

答案 1 :(得分:0)

基本上,您只需连接列表,对结果进行排序,并在计算重复元素时对其进行运行。也许itertools.groupby可以提供帮助:https://docs.python.org/2/library/itertools.html#itertools.groupby

答案 2 :(得分:0)

f = [('one',2), ('two',3)]

g = [('one',2), ('three',4)]

print set(f) | set(g)

set([('three', 4), ('one', 2), ('two', 3)])
[Finished in 0.2s]

也许更容易。 enter image description here

答案 3 :(得分:0)

您可以使用默认字典执行此操作:

from collections import defaultdict

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

mydict = defaultdict(int)

for each in foo+bar:
    mydict[each[0]]+=each[1]

foobar = [[x,y] for x,y in mydict.items()]

通过使用默认字典,您可以确保如果第一个值不在您的字典中,则不会出现密钥错误。

如果您的列表维护了一个可预测的结构,就像您发布的那样,您应该能够在将它们应用到您的字典时对它们进行可靠的索引。

底部的列表理解为您提供了以

开头的结构