2016-12-03 74 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]))