问题:for循环居然不能删除列表中所有指定值
n9 = ['1', '', '3', '', '', '6', '', '', '']for i in n9:if i == '':n9.remove(i)print("数组长度在Remove后-1:", len(n9))print(n9)
输出结果
数组长度在Remove后-1: 9数组长度在Remove后-1: 8数组长度在Remove后-1: 7数组长度在Remove后-1: 7数组长度在Remove后-1: 6数组长度在Remove后-1: 5['1', '3', '6', '', '']
原因
for的计数器是依次递增的,直接对列表进行remove(等处理)后,列表的内容和元素个数已被更改。
删除后会导致遍历重复的值,并且实际个数比预期个数-1。
解决方案
不对列表直接进行修改,赋值给新的变量储存。
n9 = ['1', '', '3', '', '', '6', '', '1', '1', '1', '', '', '6', '', '']filtered = []for i in n9:if i == "":# print("仅过滤空元素")passelse:filtered.append(i)print(filtered)
输出结果
加强版
通过列表过滤/删除多个指定字符串:
listWithNull = ['1', '', '3', '', '', '6', '', '1', '1', '1', '', '', '6', '', '']list2Filter = ["", "1"]listFiltered = []for i in listWithNull:if i in list2Filter:# print("通过list过滤多个元素")passelse:listFiltered.append(i)print(listFiltered)
23.02.15
背景
有需要遍历处理的列表数据,嵌套着一个list(比如[“字段1”,“字段2”,“字段3”])。
list_Level1 = ["Level1_0" , "Level1_1" , "Level1_2"]list_Level2 = ["Level2_0" , "Level2_1" , "Level2_2"]
错误的原始代码
for iL1 in list_Level1:print( "\n" + iL1 )for iL2 in list_Level2:print( iL2 )list_Level2.remove( iL2 )
结果

