# 删除字符串为空的元素
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的长度,导致出现意料之外的结果。
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)