移除list中所有的””空元素

  • Post author:
  • Post category:其他


移除list中的””空元素

list_1 = ['', '0', '', 's', '', '', '', '', '', '', '6']
print(len(list_1))
for i in list_1:
    if i == '':
        list_1.remove(i)
    else:
        pass
print(list_1)
print(len(list_1))

输出结果

11
['0', 's', '', '', '', '6']
6

问题:为什么列表中还是有””空元素,但是如果我的list_1中空元素个数变化的话,输出结果list_1中的空元素个数也不相同

原因:for的计数器是依次递增的,但列表的内容已通过remove更改,计数器为0的时候判定list中的第一个元素,计数器为1的时候判断列表中的第二个元素,但是原来的列表已经发生了变化,第一个元素为空已经被删除,第二个元素就成了第一个元素,所以判定的时候就会跳过remove后的第一个元素,所以后面可能会跳过很多“”空元素;这种情况可以使用while处理

list_1 = ['', '0', '', 's', '', '', '', '', '', '', '6', '', '', '', '', '', '']
print(len(list_1))

while "" in list_1:
    list_1.remove("")

print(list_1)
print(len(list_1))



版权声明:本文为youarenotin原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。