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

时间:2011-05-19 17:03:12

标签: python list dictionary count unique

必须有一个更好的方法来编写这个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.'

非常感谢

4 个答案:

答案 0 :(得分:11)

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

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

答案 1 :(得分:2)

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 

答案 2 :(得分:0)

count = len(set(p['Nationality'] for p in people))
print 'There are' + str(count) + 'nationalities in this list.'

答案 3 :(得分:0)

len(set(x['Nationality'] for x in p))