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
4 个解决方案
#1
11
A better way is to build the set
directly from the dictionaries:
更好的方法是直接从字典构建集合:
print len(set(p['Nationality'] for p in people))
#2
2
There is collections
module
有收集模块
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
#3
0
len(set(x['Nationality'] for x in p))
#4
0
count = len(set(p['Nationality'] for p in people))
print 'There are' + str(count) + 'nationalities in this list.'
#1
11
A better way is to build the set
directly from the dictionaries:
更好的方法是直接从字典构建集合:
print len(set(p['Nationality'] for p in people))
#2
2
There is collections
module
有收集模块
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
#3
0
len(set(x['Nationality'] for x in p))
#4
0
count = len(set(p['Nationality'] for p in people))
print 'There are' + str(count) + 'nationalities in this list.'