您可以使用collections.Counter 和generator expression 来计算每个国家/地区出现在列表中的次数。之后,您可以使用most_common 方法来获取出现最多的那个。代码将如下所示:
from collections import Counter
aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005}]
[(country, _)] = Counter(x['country'] for x in aList).most_common(1)
print(country)
# Output: japan
下面是每个部分的作用的演示:
>>> from collections import Counter
>>> aList = [{'country': 'japan', 'city': 'tokyo', 'year': '1995'}, {'country': 'japan', 'city': 'hiroshima', 'year': '2005'}, {'country': 'norway', 'city': 'oslo', 'year': '2005'}]
>>> # Get all of the country names
>>> [x['country'] for x in aList]
['japan', 'japan', 'norway']
>>> # Total the names
>>> Counter(x['country'] for x in aList)
Counter({'japan': 2, 'norway': 1})
>>> # Get the most common country
>>> Counter(x['country'] for x in aList).most_common(1)
[('japan', 2)]
>>> # Use iterable unpacking to extract the country name
>>> [(country, _)] = Counter(x['country'] for x in aList).most_common(1)
>>> print(country)
japan
>>>