2015-06-22 19 views
0

指數閱讀關於這個問題How to count the frequency of the elements in a list?我不知道怎麼算的東西頻率的答案後,並在同一時間retreive一些額外的信息,通過類似的索引。例如使用的陣列櫃的一個值,同時保持其它值

a = ['fruit','Item#001'] 
b = ['fruit','Item#002'] 
c = ['meat','Item#003'] 
foods = [a,b,c] 

現在我想要計算清單食品中水果的數量。如果我在每個數組a,b和c的第一個索引上使用計數器,結果將會有水果的數量,但我無法訪問它是哪個項目。實質上,如果我使用most_common,我會得到水果出現次數的列表,如('fruit',2),我如何從這兩次出現中獲得所有項目。

我想避免使用屬性,像這樣的問題Python how to use Counter on objects according to attributes

例,哪裏會做我喜歡什麼,不一定是反法實際執行。

counts = Counter(foods) 
counts.most_common(10) 
print counts 
-> (('fruit',2)('meat',1)) 
print counts[0].Something_Like_Expand_Method() 
-> ['fruit','Item#001'],['fruit','Item#002'] 

回答

4

要算多久一個值出現,並在同一時間,你要選擇那些價值觀,你只需選擇那些價值觀和算你選擇多少:

fruits = [f for f in foods if f[0] == 'fruit'] 
fruit_count = len(fruits) 

如果您需要要做到這一點的所有條目,你真的想您的項目,使用字典:

food_groups = {} 
for food in foods: 
    food_groups.setdefault(food[0], []).append(food[1]) 

此時您可以要求任何的組,再加上其長度:

fruit = food_groups['fruit'] 
fruit_count = len(fruit) 

如果您還需要了解哪些食品集團是最常見的,然後你可以只使用max()功能:

most_common_food = max(food_groups, key=lambda f: len(food_groups[f])) # just the food group name 
most_common_food_items = max(food_groups.values(), key=len) # just the food group name 

,或者你可以創建一個Counter基團通過在字典映射密鑰傳遞到值長度:

group_counts = Counter({f: len(items) for f, items in food_groups.iteritems()}) 
for food, count in group_counts.most_common(2): 
    print '{} ({}):'.format(food, count) 
    print ' items {}\n'.format(', '.join(food_groups[food])) 

演示:

>>> from collections import Counter 
>>> a = ['fruit','Item#001'] 
>>> b = ['fruit','Item#002'] 
>>> c = ['meat','Item#003'] 
>>> foods = [a,b,c] 
>>> food_groups = {} 
>>> for food in foods: 
...  food_groups.setdefault(food[0], []).append(food[1]) 
... 
>>> food_groups 
{'fruit': ['Item#001', 'Item#002'], 'meat': ['Item#003']} 
>>> group_counts = Counter({f: len(items) for f, items in food_groups.iteritems()}) 
>>> for food, count in group_counts.most_common(2): 
...  print '{} ({}):'.format(food, count) 
...  print ' items {}\n'.format(', '.join(food_groups[food])) 
... 
fruit (2): 
    items Item#001, Item#002 

meat (1): 
    items Item#003 
+0

這是很好的,這似乎是羣體是真的要走的路。 – user1938107

相關問題