以下是一些示例代码:
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
属性,并且它不是唯一的属性,则表示该字典已经处理完毕,将其添加到新列表中。然后,我们将当前元素添加到当前字典中。最后,我们检查最后一个字典是否为空,并将其添加到新列表中(如果不为空)。