gpt4 book ai didi

python - 更新字典列表中的值

转载 作者:太空宇宙 更新时间:2023-11-03 14:20:20 26 4
gpt4 key购买 nike

我有一个类似这样的字典列表:

users=[{"name": "David", "team": "reds", "score1": 100, "score2": 20,},
{"name": "David", "team": "reds", "score1": 20, "score2": 60,},
{"name": "David", "team": "blues", "score1": 10, "score2": 70,}]

并且真的很想得到一个新的处理过的字典列表,比如

summary=[{"team": "reds", "total1": 120, "total2": 80,},
{"team": "blues", "total1": 120, "total2": 80,}]

最好只循环一次原始数据。我可以创建一个字典,其中包含每个用户键的总值

summary = dict()
for user in users:
if not user['team'] in summary:
summary[user['team']]=float(user['score1'])
else:
summary[user['team']]+=float(user['score1'])

给予

summary = {'reds': 120,'blues': 10}

但是我正在努力生成字典列表,我能得到的最接近的方法是在团队的第一个实例中创建一个字典,然后尝试在后续出现时附加到它的值...

summary = []
for user in users:
if any(d['team'] == user['team'] for d in summary):
# append to values in the relevant dictionary
# ??
else:
# Add dictionary to list with some initial values
d ={'team':user['team'],'total1':user['score1'],'total2':user['score2']}
summary.append(dict(d))

...它变得一团糟...我是不是以完全错误的方式处理这件事?您可以更改列表中字典中的值吗?

谢谢

最佳答案

我认为这是使用 pandas 的好案例python 库:

>>> import pandas as pd
>>> dfUsers = pd.DataFrame(users)
>>> dfUsers

name score1 score2 team
0 David 100 20 reds
1 David 20 60 reds
2 David 10 70 blues

>>> dfUsers.groupby('team').sum()

score1 score2
team
blues 10 70
reds 120 80

如果你真的想把它放入dict:

>>> dfRes = dfUsers.groupby('team').sum()
>>> dfRes.columns = ['total1', 'total2'] # if you want to rename columns
>>> dfRes.reset_index().to_dict(orient='records')

[{'team': 'blues', 'total1': 10, 'total2': 70},
{'team': 'reds', 'total1': 120, 'total2': 80}]

另一种方法是使用 itertools.groupby :

>>> from itertools import groupby
>>> from operator import itemgetter
>>> users.sort(key=itemgetter('team'))
>>>
>>> res = [{'team': t[0], 'res': list(t[1])} for t in groupby(users, key=itemgetter('team'))]
>>> res = [{'team':t[0], 'total1': sum(x['score1'] for x in t[1]), 'total2': sum(x['score2'] for x in t[1])} for t in res]
>>> res

[{'team': 'blues', 'total1': 10, 'total2': 70},
{'team': 'reds', 'total1': 120, 'total2': 80}]

或者,如果你真的想要简单的 python:

>>> res = dict()
>>> for x in users:
if x['team'] not in res:
res[x['team']] = [x['score1'], x['score2']]
else:
res[x['team']][0] += x['score1']
res[x['team']][1] += x['score2']
>>> res = [{'team': k, 'total1': v[0], 'total2': v[1]} for k, v in res.iteritems()}]
>>> res

[{'team': 'reds', 'total1': 120, 'total2': 80},
{'team': 'blues', 'total1': 10, 'total2': 70}]

关于python - 更新字典列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28637763/

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