当我们要循环删除某个列表中的某些元素时,大家是不是第一个想到的是remove呢!不错,remove确实可以删除元素,但是当要删除多个元素,你想在for循序中使用的时候,可能会出乎你的意料,没有达到你的预期。
如下例子
# 删除字符串为空的元素
a_list = ['test_1', 'test_2', 'test_3', '', '', 'test_4', '', 'test', '']
# 在不新增列表变量的情况下使用remove
for _a in a_list:
if _a == '':
a_list.remove(_a)
print(a_list)
如上,这样子操作好像开起来没有问题,执行的时候也不会报错,但实际上,它只删除了第一个字符串为空的元素,然后就结束了,看下执行结果:
['test_1', 'test_2', 'test_3', 'test_4', 'test', '']
实际上还存在字符串为空的元素并没有被删除,这是为什么呢?
原因:在for循环中使用remove,会改变list的长度,导致出现意料之外的结果。
那这种情况,我们该如何呢?
- 第一种:可以使用append,将符合要求的,就是非空字符串追加到新的list中;最终返回这个list;
- 第二种:先复制一个同样的list,然后再使用remove,不在循序的过程中改变当前的list
- 第三种:使用列表推导式,本质上同append,但不需要新增list变量;
a_list = ['test_1', 'test_2', 'test_3', '', '', 'test_4', '', 'test', '']
new_list = []
for _a in a_list:
if _a == '':
continue
new_list.append(_a)
print(new_list)
a_list = ['test_1', 'test_2', 'test_3', '', '', 'test_4', '', 'test', '']
new_list = a_list
for _a in a_list:
if _a == '':
new_list.remove(_a)
print(new_list)
a_list = ['test_1', 'test_2', 'test_3', '', '', 'test_4', '', 'test', '']
a_list = [_a for _a in a_list if _a != '']
print(a_list)