Ant*_*ony 5 python dictionary list unique count
必须有一个更好的方法来编写这个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.'
Run Code Online (Sandbox Code Playgroud)
非常感谢
Sve*_*ach 11
更好的方法是set直接从字典构建:
print len(set(p['Nationality'] for p in people))
Run Code Online (Sandbox Code Playgroud)
count = len(set(p['Nationality'] for p in people))
print 'There are' + str(count) + 'nationalities in this list.'
Run Code Online (Sandbox Code Playgroud)