Python:有效计算字典列表中键的唯一值数
一定有更好的方法来编写Python代码,我有一个人员列表(人员是字典),我试图找到某个键的唯一值的数量(在这种情况下,该键称为National,我试图在人员列表中找到唯一国籍的数量):Python:有效计算字典列表中键的唯一值数,python,list,dictionary,count,unique,Python,List,Dictionary,Count,Unique,一定有更好的方法来编写Python代码,我有一个人员列表(人员是字典),我试图找到某个键的唯一值的数量(在这种情况下,该键称为National,我试图在人员列表中找到唯一国籍的数量): 非常感谢一个更好的方法是直接从字典构建集合: count = len(set(p['Nationality'] for p in people)) print 'There are' + str(count) + 'nationalities in this list.' print len(set(p['Na
非常感谢一个更好的方法是直接从字典构建
集合
:
count = len(set(p['Nationality'] for p in people))
print 'There are' + str(count) + 'nationalities in this list.'
print len(set(p['Nationality'] for p in people))
有
集合
模块
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
如果我读对了原文,
people
是词典的集合,而不是词典本身。
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