2010-02-12 72 views
15

我的列表(标签,计数)元组是这样的:分组Python的元组列表

[('grape', 100), ('grape', 3), ('apple', 15), ('apple', 10), ('apple', 4), ('banana', 3)] 

,从我要总结具有相同标签的所有的值(同一标签总是相邻),并返回一个列表在相同的标签顺序:

[('grape', 103), ('apple', 29), ('banana', 3)] 

我知道我可以用类似解决它:

def group(l): 
    result = [] 
    if l: 
     this_label = l[0][0] 
     this_count = 0 
     for label, count in l: 
      if label != this_label: 
       result.append((this_label, this_count)) 
       this_label = label 
       this_count = 0 
      this_count += count 
     result.append((this_label, this_count)) 
    return result 

但有一个MO重新Pythonic /优雅/有效的方式来做到这一点?

回答

23

itertools.groupby可以做你想做什么:

import itertools 
import operator 

L = [('grape', 100), ('grape', 3), ('apple', 15), ('apple', 10), 
    ('apple', 4), ('banana', 3)] 

def accumulate(l): 
    it = itertools.groupby(l, operator.itemgetter(0)) 
    for key, subiter in it: 
     yield key, sum(item[1] for item in subiter) 

>>> print list(accumulate(L)) 
[('grape', 103), ('apple', 29), ('banana', 3)] 
>>> 
+4

我喜欢用'operator.itemgetter'来代替'lambda'。 – jathanism 2010-02-12 01:48:37

+1

这要求列表按第一个键排序。如果它尚未排序,那么ghostdog74的defaultdict方法是更好的解决方案。 – 2016-10-10 21:05:35

5

使用itertools和list解析

import itertools 

[(key, sum(num for _, num in value)) 
    for key, value in itertools.groupby(l, lambda x: x[0])] 

编辑:为gnibbler指出:如果l是不是已经排序与sorted(l)更换。

+4

使用GROUPBY,您必须首先确保序列pregrouped(所有的“葡萄”相邻,等等)。一种方法是首先对序列进行排序 – 2010-02-12 01:30:12

+0

OP声称标签已经分组。 – 2010-02-12 01:31:59

+0

@Thomas Wouters,是的,你是正确的(“相同的标签总是相邻的”) – 2010-02-12 01:40:12

3
import collections 
d=collections.defaultdict(int) 
a=[] 
alist=[('grape', 100), ('banana', 3), ('apple', 10), ('apple', 4), ('grape', 3), ('apple', 15)] 
for fruit,number in alist: 
    if not fruit in a: a.append(fruit) 
    d[fruit]+=number 
for f in a: 
    print (f,d[f]) 

输出

$ ./python.py 
('grape', 103) 
('banana', 3) 
('apple', 29) 
3
>>> from itertools import groupby 
>>> from operator import itemgetter 
>>> L=[('grape', 100), ('grape', 3), ('apple', 15), ('apple', 10), ('apple', 4), ('banana', 3)] 
>>> [(x,sum(map(itemgetter(1),y))) for x,y in groupby(L, itemgetter(0))] 
[('grape', 103), ('apple', 29), ('banana', 3)] 
0

或者更简单更可读的答案(不itertools):

pairs = [('foo',1),('bar',2),('foo',2),('bar',3)] 

def sum_pairs(pairs): 
    sums = {} 
    for pair in pairs: 
    sums.setdefault(pair[0], 0) 
    sums[pair[0]] += pair[1] 
    return sums.items() 

print sum_pairs(pairs) 
1

我的版本不itertools
[(k, sum([y for (x,y) in l if x == k])) for k in dict(l).keys()]