groupby および list、dict および generator 内包表記を使用した別のソリューション:
list1=[{'a':'apples', 'b':'snack','count':2},{'a':'apples','b':'lunch','count':3},{'a':'apples','b':'snack','count':3}]
from itertools import groupby
list1.sort()
group_func = lambda x: {key:val for key, val in x.iteritems() if key!='count'}
list2 = [dict(k, count = sum(item['count'] for item in items)) for k, items in groupby(list1, group_func)]
[{'a': 'apples', 'count': 3, 'b': 'lunch'}, {'a': 'apples', 'count': 5, 'b': 'snack'}]
説明:
- grouper 関数は項目を受け取り、dict-comprehension を使用して「カウント」項目なしでサブ辞書を返します。
- 次に、groupby は、同じ subdict を持つすべての元のリスト項目を収集します
- 最後に、リスト内包表記はそれらのグループを反復し、(現在はジェネレータ内包表記を使用して) カウント項目を合計します。
短所:
- 読みにくい。
- groupby を機能させるには、ソートする必要があるため、処理が遅くなる可能性があります。
長所:
- list1 がすでにソートされている場合、これはおそらくより高速です。(理解は一般的にPythonの方が速いため)
- 短い。(ほとんど理解できない1行で書くことさえできます:))