[英]Python: efficient counting number of unique values of a key in a list of dictionaries
必須有一個更好的方法來編寫這個Python代碼,我有一個人的列表(人們是字典),我試圖找到某個鍵的唯一值的數量(在這種情況下,鍵稱為國籍,我是試圖找到人名單中的獨特國籍數量):
no_of_nationalities = []
for p in people:
no_of_nationalities.append(p['Nationality'])
print 'There are', len(set(no_of_nationalities)), 'nationalities in this list.'
非常感謝
更好的方法是直接從字典構建set
:
print len(set(p['Nationality'] for p in people))
有collections
模塊
import collections
....
count = collections.Counter()
for p in people:
count[p['Nationality']] += 1;
print 'There are', len(count), 'nationalities in this list.'
這樣你就可以統計每個國籍。
print(count.most_common(16))#print 16 most frequent nationalities
count = len(set(p['Nationality'] for p in people))
print 'There are' + str(count) + 'nationalities in this list.'
len(set(x['Nationality'] for x in p))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.