计算字典列表中某个值的出现次数

2024-06-07 08:16:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道我是否会以这种方式存储信息,但它是这样呈现给我的。在

假设我有一个字典列表,记录了目击不明飞行物的细节,如下所示:

aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005} ... etc]

我知道如何计算一个列表中出现的次数,但由于涉及词典,我不确定该怎么做。在

例如,如果我想知道哪个国家发现不明飞行物最多,我该怎么做?在


Tags: 信息city列表字典方式记录yearcountry
2条回答

您可以使用^{}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

以下是每个部分的功能演示:

^{pr2}$

下面是一个简洁的版本:

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()

输出

^{pr2}$

相关问题 更多 >

    热门问题