输入:
[['a', 2], ['b',1]] (sorted by value)
[['b', 2], ['c', 1]]
输出:
[['b', 3], ['a', 2], ['c', 1]]
任何pythonic方式?当然,在 Python 中! (最好是 2.6 倍) 谢谢!
最佳答案
使用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)]
如果列表包含重复项,则需要将 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)]
对于 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)]
关于python - 做 "[[' a', 2], ['b' ,1]] + [ ['b' , 2], ['c' , 1]] = [ ['b' , 3], ['a' , 2], 0x1045,67910"的任何 pythonic 方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20139002/