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

5

在这段Python代码中,我有一个人员列表(人员是字典),我正在尝试查找特定键(在本例中称为Nationality)的唯一值数量(即要查找人员列表中唯一国籍的数量)。希望能有更好的写法:

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个回答

11

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

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

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 

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

1
如果我正确地阅读了原始帖子,people 是一个字典的集合,但不是一个字典本身。 - Sven Marnach

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接