Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:有效计算字典列表中键的唯一值数_Python_List_Dictionary_Count_Unique - Fatal编程技术网

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

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

一定有更好的方法来编写Python代码,我有一个人员列表(人员是字典),我试图找到某个键的唯一值的数量(在这种情况下,该键称为National,我试图在人员列表中找到唯一国籍的数量):


非常感谢

一个更好的方法是直接从字典构建
集合

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