今天在学到列表的删除操作时,突然想到如果要删除一个列表中存在多个相同的对象时,应该怎么要操作?
列表删除操作有三个函数可实现
names = ['a', 'b', 'c', 'd', 'e']
del names[0]
name
[‘b’, ‘c’, ‘d’, ‘e’]
names = ['a', 'b', 'c', 'd', 'e']
del names[0:3]
names
[ ‘d’, ‘e’]
names = ['a', 'b', 'c', 'd', 'e']
del names
names
‘’’
NameError Traceback (most recent call last)
in
1 names = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
2 del names
----> 3 names
NameError: name ‘names’ is not defined
‘’’
names = ['a', 'b', 'c', 'd', 'e']
del names[6]
names
IndexError Traceback (most recent call last)
in
1 names = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
----> 2 del names[6]
3 names
IndexError: list assignment index out of range
names = ['a', 'b', 'c', 'd', 'e']
names.pop(0)
names
‘a’
[‘b’, ‘c’, ‘d’, ‘e’]
names = ['a', 'b', 'c', 'd', 'e']
names.pop(5)
names
IndexError Traceback (most recent call last)
in
1 names = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
----> 2 names.pop(5)
3 names
IndexError: pop index out of range
names = ['a', 'b', 'c', 'd', 'b']
names.remove('b')
names
[‘a’, ‘c’, ‘d’, ‘b’]
names = ['a', 'b', 'c', 'd', 'e']
names.remove('f')
ValueError Traceback (most recent call last)
in
1 names = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
----> 2 names.remove(‘f’)
ValueError: list.remove(x): x not in list
如果使用for循环,每循环一次,删除一个相同的元素,直到所有该元素全部删除
names = ['a', 'b', 'c', 'd' ,'c' ,'c' ,'c']
for name in names:
names.remove('c')
names
[‘a’, ‘b’, ‘d’]
这样一看好像问题就解决了,把names中所有的c字符串全部都删除了,但问题好像没那么简单
当在字符串中多写几个c后,发现后面的c竟然删不掉,且列表中的值越多,遗留下来的的c就越多,这是为什么?
names = ['a', 'b', 'c', 'd', 'c', 'c', 'c', 'c', 'c', 'c']
for name in names:
names.remove('c')
names
[‘a’, ‘b’, ‘d’, ‘c’, ‘c’]
看看pop和del函数是不是也存在这样的问题,默认删除最后一个一个元素,看看运行的结果
names = ['shunquan', 'caocao', 'liubei', 'zhugeliang']
for name in names:
names.pop(-1)
names
names = ['shunquan', 'caocao', 'liubei', 'zhugeliang']
for name in names:
del names[-1]
names
输出的结果都没有删除干净
[‘shunquan’, ‘caocao’]
那么应该是我for循环函数没有理解透彻,肯定是在哪一步跳出循环了,导致后续的结果没有执行成功,把所有相关的字符打印出来核查原因
names = ['shunquan', 'caocao', 'liubei', 'zhugeliang']
for name in names:
print(f'删除最后一个元素{names.pop(-1)},剩下的元素{names},传递给{name}的元素')
删除最后一个元素zhugeliang,剩下的元素[‘shunquan’, ‘caocao’, ‘liubei’],传递给shunquan的元素
删除最后一个元素liubei,剩下的元素[‘shunquan’, ‘caocao’],传递给caocao的元素
看到返回结果,问题原因找到了
利用列表长度来定义循环次数,列表有多少字符串(或者存在多少个相同元素),就循环几次
names = ['shunquan', 'caocao', 'liubei', 'zhugeliang']
for name in range(len(names)):
names.pop(-1)
names
[]
names = ['a', 'b', 'c', 'd', 'c', 'c', 'd', 'c', 'c', 'c', 'c', 'c']
for name in range(names.count('c')):
names.remove('c')
names
[‘a’, ‘b’, ‘d’, ‘d’]
刚接触编程,第一次写博客,本篇可能会出现一些门外汉的语句与思考方式,望看到本篇的各位大佬海涵,本篇只是记录下自己的学习心得,为了方便后续复习与思考,解决的方法肯定不止只一种,后续如果学到了,继续更新;