数据是
people = [{'name': 'A', 'shirtcolor': 'blue', 'money': '100', 'spent': '50'},
{'name': 'B', 'shirtcolor': 'red', 'money': '70', 'spent': '50'},
{'name': 'C', 'shirtcolor': 'yellow', 'money': '100', 'spent': '70'},
{'name': 'D', 'shirtcolor': 'blue', 'money': '200', 'spent': '110'},
{'name': 'E', 'shirtcolor': 'red', 'money': '130', 'spent': '50'},
{'name': 'F', 'shirtcolor': 'yellow', 'money': '200', 'spent': '70'},
{'name': 'G', 'shirtcolor': 'green', 'money': '100', 'spent': '50'}]
您只需要一个字典,其中颜色是键,值是一个键为“money”和“spent”的字典。然后你可以在那里添加所有条目。
color_sum = dict()
for entry in people:
if entry['shirtcolor'] not in color_sum:
color_sum[entry['shirtcolor']] = {'money':0, 'spent':0}
color_sum[entry['shirtcolor']]['money'] += int(entry['money'])
color_sum[entry['shirtcolor']]['spent'] += int(entry['spent'])
使用 defaultdict 确实使这更容易。
from collections import defaultdict
color_sum = defaultdict(lambda: {'money':0, 'spent':0})
for entry in people:
color_sum[entry['shirtcolor']]['money'] += int(entry['money'])
color_sum[entry['shirtcolor']]['spent'] += int(entry['spent'])
color_sum 中的结果数据将是这样的:
{'blue': {'money': 300, 'spent': 160},
'red': {'money': 200, 'spent': 100},
'yellow': {'money': 300, 'spent': 140},
'green': {'money': 100, 'spent': 50}}
现在您可以获得所需的信息。
money_red_blue = color_sum["red"]["money"] + color_sum["blue"]["money"]
money_yellow_green = color_sum["yellow"]["money"]+ color_sum["green"]["money"]
print(f'Total money: {money_red_blue} and {money_yellow_green}')
这将输出Total money: 500 and 400
评论中的问题是如何从没有绿色和黄色之一的衬衫中获得所有的钱。在这种情况下,我们将不得不遍历字典中的聚合数据,并排除键为“green”和“yellow”的项目。
money = 0
for k, v in color_sum.items():
if k not in {'green', 'yellow'}:
money += v['money']
print(money)
或者作为 sum 和生成器的单行代码:
money = sum(v['money'] for k, v in color_sum.items() if k not in {'green', 'yellow'})
print(money)