简体   繁体   English

Python:有效计算字典列表中键的唯一值的数量

[英]Python: efficient counting number of unique values of a key in a list of dictionaries

There must be a better way of writing this Python code where I have a list of people (people are dictionaries) and I am trying to find the number of unique values of a certain key (in this case the key is called Nationality and I am trying to find the number of unique nationalities in the list of people): 必须有一个更好的方法来编写这个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.'

Many thanks 非常感谢

更好的方法是直接从字典构建set

print len(set(p['Nationality'] for p in people))

There is collections module collections模块

import collections
....
count = collections.Counter()
for p in people:
    count[p['Nationality']] += 1;
print 'There are', len(count), 'nationalities in this list.'

This way you can count each nationality too. 这样你就可以统计每个国籍。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM