python把数组根据某个id分组,分到不同数组

from collections import defaultdict


# 定义Organization类(保持不变)
class Organization:
    def __init__(self, organization_id, card_info_id, order_status):
        self.organization_id = organization_id
        self.payment_order_type = 'instore'
        self.card_info_id = card_info_id
        self.order_status = order_status


# 创建对象列表(保持不变)
original_list = [
    Organization(1, None, None),
    Organization(5, 1, 'ORDER_SUCCESS'),
    Organization(3, 1, 'ORDER_SUCCESS'),
    Organization(4, 2, 'ORDER'),
    Organization(2, None, None),
    Organization(5, None, None)
]

# 使用defaultdict分组
grouped_by_org_id = defaultdict(list)
for obj in original_list:
    grouped_by_org_id[obj.organization_id].append(obj)

# 将分组结果存入data列表
data = []
for org_id, group in grouped_by_org_id.items():
    # 提取每个对象的属性,转为字典格式
    group_dicts = [
        {
            'organization_id': obj.organization_id,
            'payment_order_type': obj.payment_order_type,
            'card_info_id': obj.card_info_id,
            'order_status': obj.order_status
        }
        for obj in group
    ]

    # 添加到data列表
    data.append({
        'organization_id': org_id,
        'items': group_dicts
    })

for it in data:
    print(it['organization_id'])
    for it2 in it['items']:
        print(it2['organization_id'])
        print(it2['payment_order_type'])
        print(it2['card_info_id'])
        print(it2['order_status'])

# # 打印data结构(用于调试)
import json

print(json.dumps(data, indent=2, default=str))  # 使用default=str处理None值

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大得369

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值