python关于列表操作的几行代码思考
疑问:在学习python中我打算删除长列表中最后几个特定元素,于是写了几行代码发现都不不太好,存在一些问题。
问题:l = [‘a’,‘b’,‘c’,‘a’,‘b’,‘c’],删除最后一个‘a’的元素。这个问题也可以变成删除最后几个特定元素。
第一次尝试
l = ['a','b','c','a','b','c']
times = 1
for i in reversed(l):
if times != 0 and i == 'a':
l.remove(i)
times -= 1
结果是:
['b', 'c', 'a', 'b', 'c']
问题在于remove(‘a’)只删除列表中第一个‘a’,所以结果错了。
第二次尝试
l = ['a','b','c','a','b','c']
times = 1
l = reversed(l)
for k,item in enumerate(l):
if times != 0 and item == 'a':
l.remove('a')
times -= 1
l = reversed(l)
结果是:
errors:
Instance of 'reversed' has no 'remove' member pylint(no-member) [20, 9]
The first reversed) argument is not a sequence pylint(bad-reversed-sequence) [22, 5]
这次想反转之后,删除,再反转回来。但是反转之后不支持删除操作,换成del也不行。
失败了。
第三次尝试
l = ['a','b','c','a','b','c']
times = 1
for i in reversed(range(len(l))):
if times != 0 and l[i] == 'a':
del l[i]
times -= 1
最终还是用了很c风格的代码,但是也很简短。
直接倒过来遍历来操作。
顺便一说,正向遍历的时候执行删除操作很容易出错,因为列表变了,后面元素的索引会跟着变,很容易少删漏删。