python - 做 "[[' a', 2], ['b' ,1]] + [ ['b' , 2], ['c' , 1]] = [ ['b' , 3], ['a' , 2], 0x1045,67910"的任何 pythonic 方式?

标签 python lambda functional-programming

输入:

[['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/

相关文章:

python - 如何在matplotlib中基于x轴更改直方图颜色

recursion - 在 Clojure 中将结果累积到向量中的最佳方法? (纯功能代码看起来丑陋和冗长)

python - 如何找到内置 Python 方法的源代码位置?

c++ - 根据模式用数字填充 C++ 数组

c++ - C++ 编译器是否会独立决定内联 lambda 函数及其调用者?

c# - 与 lambda 表达式中的列表进行比较

c# - 动态函数映射

javascript - angular.identity() 有什么用例的好例子吗?

python - 使用 Open CV 从线条中提取消失点

python - 如何解决 'list index out of range'