gpt4 book ai didi

python - 通过总结 Python 中的现有列表来创建一个新列表

转载 作者:行者123 更新时间:2023-12-04 07:18:10 25 4
gpt4 key购买 nike

我在 Python 中有一个这样的列表:

my_list = [
{"id":1,"symbol":"ABC","quantity":100},
{"id":2,"symbol":"PQR","quantity":500},
{"id":3,"symbol":"ABC","quantity":300},
{"id":1,"symbol":"XYZ","quantity":320},
{"id":3,"symbol":"PQR","quantity":800},
]
我想总结一个具有相似符号的数量并创建一个新列表。 new_list 将如下所示:
new_list = [
{ "symbol":"ABC","total_quantity":400,"ids":"1 3"}
{ "symbol":"PQR","total_quantity":1300,"ids":"2 3"}
{ "symbol":"XYZ","total_quantity":320,"ids":"1"}
]
我对 Python 相当陌生,尝试了一些方法但没有奏效。我可以尝试什么来实现这一目标?

最佳答案

一个不错的解决方案是使用 defaultdict这有助于按 symbol 分组,您只需要最后一步来构建 ids

from collections import defaultdict

my_list = [{"id": 1, "symbol": "ABC", "quantity": 100},
{"id": 2, "symbol": "PQR", "quantity": 500},
{"id": 3, "symbol": "ABC", "quantity": 300},
{"id": 1, "symbol": "XYZ", "quantity": 320},
{"id": 3, "symbol": "PQR", "quantity": 800}, ]

expected = defaultdict(lambda: {'symbol': '', 'ids': [], "total_quantity": 0})
for row in my_list:
expected[row['symbol']]['symbol'] = row['symbol']
expected[row['symbol']]['ids'].append(str(row['id']))
expected[row['symbol']]['total_quantity'] += row['quantity']

result = [{**x, 'ids': " ".join(x['ids'])} for x in expected.values()]

关于python - 通过总结 Python 中的现有列表来创建一个新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68662193/

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