我不知道我是否一般会以这种方式存储信息,但这就是我的呈现方式。
说我有一个字典列表记录了让我们说UFO目击的详细信息,看起来像这样:
aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005} ... etc]
我知道如何计算列表中的出现次数,但是涉及到字典,我不知道我该怎么做。
如果我想知道哪个国家的UFO最多,那我怎么能这样做?
答案 0 :(得分:3)
您可以使用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
>>>
答案 1 :(得分:1)
这是一个简洁的版本:
from collections import Counter
from operator import itemgetter
aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005}]
countries = Counter(map(itemgetter('country'), aList))
print countries.most_common()
cities = Counter(map(itemgetter('city'), aList))
print cities.most_common()
<强>输出强>
[('japan', 2), ('norway', 1)]
[('oslo', 1), ('hiroshima', 1), ('tokyo', 1)]