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

时间:2013-11-22 07:04:06

标签: 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倍) 谢谢!

6 个答案:

答案 0 :(得分:8)

对Python2.7 +使用collections.Counter

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

答案 1 :(得分:1)

由于python 2.6的集合中没有Counter类,因此这个类就可以了。可以使用defautldict,但其用法不会简化代码:

a = [['a', 2], ['b', 1]]
b = [['b', 2], ['c', 1]]
rv = {}
for k, v in a + b:
    rv[k] = rv.setdefault(k, 0) + v

预期结果的输出,转换为列表列表:

>>> map(list, sorted(rv.items(), key = lambda x: x[1], reverse=True))
[['b', 3], ['a', 2], ['c', 1]]

答案 2 :(得分:0)

只是把这个答案放在这里,但你可能希望将它们组合到一个列表中,然后计算它们:

>>> a = [['a', 2], ['b',1]]
>>> b = [['b', 2], ['c', 1]]
>>> a + b
[['a', 2], ['b', 1], ['b', 2], ['c', 1]]
>>> "".join(c*n for c, n in a+b)
'aabbbc'
>>> from collections import Counter
>>> Counter("".join(c*n for c, n in a+b))
Counter({'b': 3, 'a': 2, 'c': 1})
>>> Counter("".join(c*n for c, n in a+b)).most_common()
[('b', 3), ('a', 2), ('c', 1)]

答案 3 :(得分:0)

您可以简单地从元组列表中创建dicts(在您的案例中为列表),然后添加其计数器。

>>> from collections import Counter
>>> a = [['b', 2], ['c', 1]]
>>> b = [['a', 2], ['b',1]]
>>> sorted(dict(Counter(dict(a)) + Counter(dict(b))).items(),key= lambda x:-x[1])
[('b', 3), ('a', 2), ('c', 1)]

答案 4 :(得分:0)

很好

  
    
      

来自集合导入计数器

             

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

python 2.5和2.6中的collections.defaultdict以及2.7及更高版本中的collections.Counter

  
    
      

from collections import defaultdict

             

d = defaultdict(int)

             

表示k,v表示lis1 + lis2:

    
  
d[k] += v
  
    
      

排序(d.items(),key = lambda x:x [1],reverse = True)

    
  
 [('b', 3), ('a', 2), ('c', 1)]

答案 5 :(得分:0)

答案:

>>> from collections import Counter
>>> p = [['a', 2], ['b',1]]
>>> q = [['b', 2], ['c', 1]]
>>> m = Counter(dict(p)) + Counter(dict(q))
>>> sorted(m.items(), key=lambda x:x[1], reverse=True)
[('b', 3), ('a', 2), ('c', 1)]