2013-12-21 55 views
0

我有以下列表:如何使用groupby對列表中的元素進行分組和過濾?

itemlist=[('ItemA', '0', 'Type1'), ('ItemA', '0', 'Type2'),('ItemA', '0', 'Type1'), ('ItemB', '0', 'Type2'), ('ItemA', '1', 'Type2'), ('ItemB', '2', 'Type1'), ('ItemB', '1', 'Type3'), ('ItemB', '1', 'Type1'), ('ItemC', '1', 'Type4'), ('ItemD', '1', 'Type4')]

接下來,我編組由數量的項目,數數:

from itertools import groupby 

sortkeyfn_num = key = lambda s:s[0] 
itemlist.sort(key=sortkeyfn_num) 

result_name_dict = {} 
for key,valuesiter in groupby(itemlist, key=sortkeyfn_num): 
    result_name_dict[key] = tuple(v[1] for v in valuesiter) 

res = {} 
for k in result_name_dict.keys(): 
for i in result_name_dict.values()[result_name_dict.keys().index(k)]: 
    res.setdefault(i, 0) 
    res[i] += 1 
print k,'=', res 
res.clear() 

結果:

ItemB = {'1': 2, '0': 1, '2': 1} 
ItemC = {'1': 1} 
ItemA = {'1': 1, '0': 3} 
ItemD = {'1': 1} 

但如何將商品按數字和類型,並計算結果中的類型? 結果必須是,例如:

ItemA 0: Type1 = 2 
ItemA 0: Type2 = 1 
ItemA 1: Type2 = 1 
ItemB 0: Type2 = 1 
ItemB 1: Type3 = 2 

謝謝。

+1

又來了。時間3關閉此_exact_相同的問題:http://stackoverflow.com/questions/20724573/filter-items-by-groupby – iCodez

+0

但我需要幫助。 – bbrutall

+0

如果您需要我們的幫助,那麼您應該遵守本網站的規則並提出[主題問題](http://stackoverflow.com/help/on-topic)。那麼,這裏的編碼器將非常樂意爲您提供幫助。 – iCodez

回答

1

也許這樣?

import collections 
itemlist = [('ItemA', '0', 'Type1'), ('ItemA', '0', 'Type2'),('ItemA', '0', 'Type1'), ('ItemB', '0', 'Type2'), ('ItemA', '1', 'Type2'), ('ItemB', '2', 'Type1'), ('ItemB', '1', 'Type3'), ('ItemB', '1', 'Type1'), ('ItemC', '1', 'Type4'), ('ItemD', '1', 'Type4')] 
data_dict = collections.defaultdict(int) 
for attribute1, attribute2, attribute3 in itemlist: 
    data_dict[(attribute1, attribute2, attribute3)] += 1 
for key, value in sorted(data_dict.items()): 
    attribute1, attribute2, attribute3 = key 
    print("{attribute1} {attribute2}: {attribute3} = {value}".format(**locals())) 
+0

它的工作原理!非常感謝!) – bbrutall

0

這將是更有效的用在這裏collections.Counter

from collections import Counter 
itemlist=[('ItemA', '0', 'Type1'), ('ItemA', '0', 'Type2'),('ItemA', '0', 'Type1'), ('ItemB', '0', 'Type2'), ('ItemA', '1', 'Type2'), ('ItemB', '2', 'Type1'), ('ItemB', '1', 'Type3'), ('ItemB', '1', 'Type1'), ('ItemC', '1', 'Type4'), ('ItemD', '1', 'Type4')] 
for (a,b,c),d in sorted(Counter(itemlist).items()): 
    print "{} {}: {} = {}".format(a, b, c, d) 

輸出:

ItemA 0: Type1 = 2 
ItemA 0: Type2 = 1 
ItemA 1: Type2 = 1 
ItemB 0: Type2 = 1 
ItemB 1: Type1 = 1 
ItemB 1: Type3 = 1 
ItemB 2: Type1 = 1 
ItemC 1: Type4 = 1 
ItemD 1: Type4 = 1 
+0

感謝您的回答!) – bbrutall

相關問題