gpt4 book ai didi

python - 什么是计算字典列表中字典值的 Pythonic 方法

转载 作者:行者123 更新时间:2023-11-30 23:38:57 25 4
gpt4 key购买 nike

对于这样的列表:

for i in range(100):
things.append({'count':1})

for i in range(100):
things.append({'count':2})

计算列表中 1 的数量:

len([i['count'] for i in things if i['count'] == 1])

有什么更好的方法吗?

最佳答案

collections.Counter

>>> from collections import Counter
>>> c = Counter([thing['count'] for thing in things])
>>> c[1] # Number of elements with count==1
100
>>> c[2] # Number of elements with count==2
100
>>> c.most_common() # Most common elements
[(1, 100), (2, 100)]
>>> sum(c.values()) # Number of elements
200
>>> list(c) # List of unique counts
[1, 2]
>>> dict(c) # Converted to a dict
{1: 100, 2: 100}
<小时/>

也许你可以做这样的事情?

class DictCounter(object):
def __init__(self, list_of_ds):
for k,v in list_of_ds[0].items():
self.__dict__[k] = collections.Counter([d[k] for d in list_of_ds])

>>> new_things = [{'test': 1, 'count': 1} for i in range(10)]
>>> for i in new_things[0:5]: i['count']=2

>>> d = DictCounter(new_things)
>>> d.count
Counter({1: 5, 2: 5})
>>> d.test
Counter({1: 10})

扩展 DictCounter 来处理丢失的键:

>>> class DictCounter(object):
def __init__(self, list_of_ds):
keys = set(itertools.chain(*(i.keys() for i in list_of_ds)))
for k in keys:
self.__dict__[k] = collections.Counter([d.get(k) for d in list_of_ds])

>>> a = [{'test': 5, 'count': 4}, {'test': 3, 'other': 5}, {'test':3}, {'test':5}]
>>> d = DictCounter(a)
>>> d.test
Counter({3: 2, 5: 2})
>>> d.count
Counter({None: 3, 4: 1})
>>> d.other
Counter({None: 3, 5: 1})

关于python - 什么是计算字典列表中字典值的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13983620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com