社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

用Python计算字典列表中的出现次数

Alexander • 1 年前 • 965 次点击  

我只是想计算python列表中字典列表的出现次数。我想附加 count 基于某种过滤的出现。我看到了一个在django模型中实现这一点的示例。我只是不知道如何以纯粹的Python方式实现这种方法。

类似的方法,但有和,我只需要计数, Count the values in list of dictionaries python

dataset =[
    {
        'Country': 'GB',
        'Pollutant': 'SO2',
        'Pollution': 10,
        'Year': 2016
    },
    {
        'Country': 'AL',
        'Pollutant': 'O3',
        'Pollution': 10,
        'Year': 2015
    },
    {
        'Country': 'BE',
        'Pollutant': 'SO2',
        'Pollution': 5,
        'Year': 2016
    },
    {
        'Country': 'GB',
        'Pollutant': 'SO2',
        'Pollution': 10,
        'Year': 2016
    },
    
    {
        'Country': 'BE',
        'Pollutant': 'SO2',
        'Pollution': 10,
        'Year': 2016
    },
]

all_Years = sorted(set([v['Year'] for v in dataset]))
all_countries = sorted(set([v['Country'] for v in dataset]))
print(all_Years)
print(all_countries)

for country in all_countries:

    new_data = {
    'years': all_Years,
    'country': country,
    'data' : []
    }

   for year in all_Years:

    #some sort of filter function to apply like in django models
      f = Q(year = year, country=country)

    #apply that filltering
      country_count = dataset.filter(f).count()
      new_data['data'].append(country_count if country_count else 0)


#expected output
#new_data = 
[{'years': [2015,2016], 'country': 'AL', 'data': [1, 0]},
{'years': [2015,2016], 'country': 'BE', 'data': [1, 2]},
{'years': [2015,2016], 'country': 'GB', 'data': [0, 2]}]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/159917
 
965 次点击  
文章 [ 1 ]  |  最新文章 1 年前