删除列表中含original_y键的字典时仅能删除第一个的问题求助
问题原因
- 你手动写死了
pop(0)、pop(1)的删除逻辑,没有用到已经收集好的待删除索引列表delete_list - 即便使用
delete_list遍历删除,如果从前往后操作,前面的元素被删除后,列表后续元素的索引会整体前移,会出现漏删、删错的问题 - 你提前复制的
list1_copy在当前逻辑中完全没有发挥作用
最优解决方案
最简洁高效的方法是用列表推导式直接过滤出符合要求的元素,不需要提前收集索引,也不会出现索引偏移问题:
list1 = [{'original_x': 70, 'original_y': 134, 'original_count': 1},{'original_x': 78, 'original_y': 134, 'original_count': 2}, \ {'matched_x': 73, 'matched_y': 130, 'matched_pixel_count': 3}, {'matched_x': 73, 'matched_y': 130, 'matched_pixel_count': 3}, {'matched_x': 71, 'matched_y': 132, 'matched_pixel_count': 1}, \ {'matched_x': 76, 'matched_y': 132, 'matched_pixel_count': 2}, {'matched_x': 71, 'matched_y': 132, 'matched_pixel_count': 1}, {'matched_x': 76, 'matched_y': 132, 'matched_pixel_count': 2}, \ {'matched_x': 71, 'matched_y': 133, 'matched_pixel_count': 1}, {'matched_x': 78, 'matched_y': 133, 'matched_pixel_count': 1}, {'matched_x': 71, 'matched_y': 133, 'matched_pixel_count': 1}] # 直接过滤掉包含original_y键的字典 list1 = [d for d in list1 if 'original_y' not in d] print(list1)
沿用原索引删除逻辑的修正方案
如果需要保留你原本收集索引的逻辑,可以将待删除索引倒序排序,从后往前删除,就不会影响未处理元素的索引:
list1 = [{'original_x': 70, 'original_y': 134, 'original_count': 1},{'original_x': 78, 'original_y': 134, 'original_count': 2}, \ {'matched_x': 73, 'matched_y': 130, 'matched_pixel_count': 3}, {'matched_x': 73, 'matched_y': 130, 'matched_pixel_count': 3}, {'matched_x': 71, 'matched_y': 132, 'matched_pixel_count': 1}, \ {'matched_x': 76, 'matched_y': 132, 'matched_pixel_count': 2}, {'matched_x': 71, 'matched_y': 132, 'matched_pixel_count': 1}, {'matched_x': 76, 'matched_y': 132, 'matched_pixel_count': 2}, \ {'matched_x': 71, 'matched_y': 133, 'matched_pixel_count': 1}, {'matched_x': 78, 'matched_y': 133, 'matched_pixel_count': 1}, {'matched_x': 71, 'matched_y': 133, 'matched_pixel_count': 1}] index = 0 delete_list = [] for each_dict in list1: if 'original_y' in each_dict: print(" index is " + str(index) + " " + str(list1[index]) ) delete_list.append(index) index += 1 # 倒序遍历待删除索引,从后往前删避免索引偏移 for idx in sorted(delete_list, reverse=True): list1.pop(idx) print(list1)
内容的提问来源于stack exchange,提问作者M K
相关产品推荐
相关产品推荐

