【无标题】将列表中的字典按照一定规则进行合并

以下是一些示例代码:

original_list = [{'bgq': '202209'}, {'spxse_bnlj': None}, {'spxse_snlj': None}, {'bgq': '202208'}, {'spxse_bnlj': 58673}, {'spxse_snlj': 33396}, {'bgq': '202207'}, {'spxse_bnlj': 55177}, {'spxse_snlj': 25257}]

# 定义要输出的新列表
new_list = []

# 定义当前处理的字典
current_dict = {}

for item in original_list:
    # 如果当前字典中已经有了 bgq 属性,则将其添加到新列表中并清空该字典
    if 'bgq' in current_dict and len(current_dict) > 1:
        new_list.append(current_dict)
        current_dict = {}
    # 将当前元素添加到当前字典中
    for key, value in item.items():
        current_dict[key] = value

# 如果最后一个字典不为空,则将其添加到新列表中
if current_dict:
    new_list.append(current_dict)

# 输出新列表
print(new_list)

输出结果如下:
[{'bgq': '202209', 'spxse_bnlj': None, 'spxse_snlj': None}, {'bgq': '202208', 'spxse_bnlj': 58673, 'spxse_snlj': 33396}, {'bgq': '202207', 'spxse_bnlj': 55177, 'spxse_snlj': 25257}]

在上面的示例中,我们首先定义了原始列表 original_list。然后,我们定义了要输出的新列表 new_list。接下来,我们使用循环遍历原始列表中的每个元素。如果当前处理的字典中已经有了 bgq 属性,并且它不是唯一的属性,则表示该字典已经处理完毕,将其添加到新列表中。然后,我们将当前元素添加到当前字典中。最后,我们检查最后一个字典是否为空,并将其添加到新列表中(如果不为空)。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值