2016-12-03 70 views
0

我在python列表中对列表进行排序。但我也需要计算列表元素。下面的列表:如何统计python列表中的列表元素

fruit = [ 
    ['Apple', 'S+'], ['Apple', 'S+'], ['Apple', 'B+'], 
    ['Grape', 'B+'], ['Grape', 'C+'] 
] 

结果:

{'Apple':{'total':3, 'S+':2, 'B+':1}, 'Grape':{'total':2, 'B+':1, 'C+':1}} 

我上面有导致通过几个并同时。但我想要简单的方法。有美丽和简单的方法来获得以上结果吗?

回答

0

东西接近你想要的,使用collections.defaultdictcollections.Counter

我试图让它尽可能pythonic。

import collections 

fruit = [ 
    ['Apple', 'S+'], ['Apple', 'S+'], ['Apple', 'B+'], 
    ['Grape', 'B+'], ['Grape', 'C+'] 
] 


d = collections.defaultdict(lambda : [collections.Counter(),0]) 

for k,v in fruit: 
    d[k][0][v]+=1 
    d[k][1]+=1 

print(dict(d)) # convert to dict for readability when printing 

结果:

{'Grape': [Counter({'B+': 1, 'C+': 1}), 2], 'Apple': [Counter({'S+': 2, 'B+': 1}), 3]} 

细节:

  • 创建,当键不存在,默认为创建一个2元素列表的字典。此元素列表由一个collections.Counter对象和一个整数(用于全局计数)构成,并计数元素和总数。
  • 循环“元组”。
0
unique, counts = numpy.unique(fruits, return_counts=True) 

return_counts加入unique在numpy的1.9.0

1

itertools.groupby的乐趣。

>>> result = {} 
>>> for k, v in groupby(fruit,lambda x:x[0]): 
...  value = list(v) 
...  result[k] = {'total':len(value)} 
...  for i,j in groupby(value, lambda x:x[1]): 
...   result[k].update({i:len(list(j))}) 

输出:

{'Grape': {'total': 2, 'C+': 1, 'B+': 1}, 'Apple': {'total': 3, 'S+': 2, 'B+': 1}} 

N.B.

尽管在这里不需要,但在应用groupby之前排序集合总是明智的。对于这个例子:

fruit = sorted(fruit, key= lambda x:(x[0],x[1]))