如何根据主列表LIST_5规则同步删除多个关联列表的同索引元素
多关联列表同步按索引删除实现方案
你原有代码的遍历中直接删除列表元素的写法存在逻辑漏洞:遍历动态变化的列表时,删除元素会导致后续元素索引前移,出现漏删问题,当前输出正确仅为测试用例巧合。
正确实现思路为:先基于主列表LIST_5筛选出需要保留的索引集合,再用该索引统一过滤所有关联列表,即可实现同步删除效果,完整代码如下:
LIST_1 = ['english', 'english', 'french', 'english', 'english', 'english'] LIST_2 = ['documentation', 'music', 'position', 'social media', 'microeconomics', 'financial equations'] LIST_3 = ['ea_12', 'ea_12', 'ea_12', 'ea_12', 'ea_12', 'ea_12'] LIST_4 = ['141031', '141032', '141033', '141034', '141035', '141036'] LIST_5 = ['allowed', 'allowed', 'rejected', 'allowed', 'rejected', 'allowed'] # 收集所有需要保留的索引:即LIST_5中值为allowed的位置 keep_indexes = [idx for idx, val in enumerate(LIST_5) if val == 'allowed'] # 批量过滤所有关联列表 LIST_1 = [LIST_1[i] for i in keep_indexes] LIST_2 = [LIST_2[i] for i in keep_indexes] LIST_3 = [LIST_3[i] for i in keep_indexes] LIST_4 = [LIST_4[i] for i in keep_indexes] LIST_5 = [LIST_5[i] for i in keep_indexes] # 测试输出 print(LIST_1) print(LIST_2) print(LIST_3) print(LIST_4) print(LIST_5)
运行后输出和你期望的结果完全一致。
如果后续关联列表数量增加,可以把所有列表放到统一容器中批量处理,简化代码:
all_lists = [LIST_1, LIST_2, LIST_3, LIST_4, LIST_5] all_lists = [[lst[i] for i in keep_indexes] for lst in all_lists] LIST_1, LIST_2, LIST_3, LIST_4, LIST_5 = all_lists
内容的提问来源于stack exchange,提问作者B A C H A S H
相关产品推荐
相关产品推荐

