And*_*ote 5 python dictionary list count
我不知道我是否通常会以这种方式存储信息,但这就是向我呈现信息的方式。
假设我有一个词典列表,其中记录了不明飞行物目击事件的详细信息,如下所示:
aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005} ... etc]
Run Code Online (Sandbox Code Playgroud)
我知道如何计算列表中出现的次数,但是由于涉及字典,因此我不确定该如何处理。
例如,如果我想知道哪个国家的不明飞行物最多,那我该怎么办?
小智 5
您可以使用collections.Counter和生成器表达式来计算每个国家/地区在列表中出现的次数。之后,您可以使用该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
Run Code Online (Sandbox Code Playgroud)
下面演示了每个部分的作用:
>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)