2016-12-03 10 views
0

リスト内のリストをソートしました。私もリストの要素を数える必要があります。リスト内のリスト要素を数える方法

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を使用してください。

私は可能な限りピジョンソニックにしようとしました。

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はnumpyの1.9.0でunique

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])) 
関連する問題