任何pythonic方式做"[['a',2],['b',1]] + [['b',2],['c',1]] = [['b',3] ,['a',2],['c',1]]"?

Kan*_*ane 2 python lambda functional-programming

输入:

[['a', 2], ['b',1]] (sorted by value)
[['b', 2], ['c', 1]]
Run Code Online (Sandbox Code Playgroud)

输出:

[['b', 3], ['a', 2], ['c', 1]]
Run Code Online (Sandbox Code Playgroud)

任何pythonic方式?当然,在Python中!(最好是2.6倍)谢谢!

Ash*_*ary 8

使用collections.Counter了Python2.7 +:

>>> from collections import Counter
>>> lis1 = [['a', 2], ['b',1]]
>>> lis2 = [['b', 2], ['c', 1]]
>>> c = Counter(dict(lis1)) + Counter(dict(lis2))
>>> c.most_common()
[('b', 3), ('a', 2), ('c', 1)]
Run Code Online (Sandbox Code Playgroud)

如果列表包含重复项,则需要将Counter示例修改为:

>>> lis1 = [['a', 2], ['b',1], ['b',5]]
>>> lis2 = [['b', 2], ['c', 1], ['a', 10]]
>>> from itertools import chain
>>> from collections import Counter
>>> c = sum((Counter(dict([x])) for x in chain(lis1, lis2)), Counter())
>>> c.most_common()
[('a', 12), ('b', 8), ('c', 1)]
Run Code Online (Sandbox Code Playgroud)

对于2.5 <= Python <= 2.6使用collections.defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for k, v in lis1 + lis2:
    d[k] += v
...     
>>> sorted(d.items(), key=lambda x:x[1], reverse=True)
[('b', 3), ('a', 2), ('c', 1)]
Run Code Online (Sandbox Code Playgroud)