gpt4 book ai didi

python - 在 python 中转换列表

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:18 25 4
gpt4 key购买 nike

大家好我有一个json

[{"seller_id": 3, "item": {"product_id": 4, "amount": 1, "id": 9}},
{"seller_id": 1, "item": {"product_id": 1 , "amount": 2, "id": 10}},
{"seller_id": 3, "item": {"product_id": 3, "amount": 2, "id": 11}},
{"seller_id ": 1," item ": {" product_id ": 2," amount ": 2," id ": 12}}]

我想组合在一起,这意味着相同的卖家会再次对商品进行分组

返回结果如下:

[{"seller_id": 3, "list_item": [{"product_id": 4, "amount": 1, "id": 9},
{"product_id": 3, "amount": 2, "id": 11}]},
{"seller_id": 1, "list_item": [{"product_id": 1, "amount": 2, "id": 10},
{"product_id": 1, "amount": 2, "id": 10}, {"product_id": 2, "amount": 2, "id": 12}]}]

谁有想法?

最佳答案

使用 itertools.groupby (并假设一些键和值周围的奇怪间距是偶然的):

from itertools import groupby
values = [{"seller_id": 3, "item": {"product_id": 4, "amount": 1, "id": 9}},
{"seller_id": 1, "item": {"product_id": 1, "amount": 2, "id": 10}},
{"seller_id": 3, "item": {"product_id": 3, "amount": 2, "id": 11}},
{"seller_id": 1, "item": {"product_id": 2, "amount": 2, "id": 12}}]

def get_seller_id(d):
return d['seller_id']

groups = []
for seller_id, items in groupby(sorted(values, key=get_seller_id), get_seller_id):
groups.append({'seller_id': seller_id, 'list_item': list(items)})

print(groups)

关于python - 在 python 中转换列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54228100/

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