Python3 循环删除列表中的指定变量

写这篇博客来记录犯了索引的错,记住列表的索引是从0开始的,不是从1开始的

# #使用循环删除vale这个值
motorcycles = ['vale','calida','torrod','slides','vale']
show_message = []
print(motorcycles)
for i in range(len(motorcycles)-1):
    print(len(motorcycles))
    show_message = motorcycles[i]
    if show_message == 'vale':
        motorcycles.remove('vale')
        print(motorcycles)
    else:
        continue

在range当中len(motocycles)=5,而索引只有0,1,2,3,4,所以说,是不对的,如果从1开始的话,那么会直接从'calida'这个元素开始进行比对,虽然在pycharm中会运行出来结果,但是会报索引错误。

现在的运行结果如下:

/usr/bin/python3.6 /home/arnyeksec/PycharmProjects/arnyeksec/List_增删改查.py
['vale', 'calida', 'torrod', 'slides', 'vale']
5
['calida', 'torrod', 'slides', 'vale']
4
4
4
['calida', 'torrod', 'slides']

Process finished with exit code 0
做一下简化,可以将代码改成:

motorcycles = ['vale','calida','torrod','slides','vale']
show_message = []
for i in range(len(motorcycles)-1):
    show_message = motorcycles[i]
    if show_message == 'vale':
        motorcycles.remove('vale')
    else:
        continue
print(motorcycles)

这样只需要九行代码就可以解决这个问题,运行结果如下:

/usr/bin/python3.6 /home/arnyeksec/PycharmProjects/arnyeksec/List_增删改查.py
['calida', 'torrod', 'slides']

Process finished with exit code 0

这样保证直接出结果,看起来比较方便,但是在写的过程中还是建议要多写几个print语句,方便debug

猜你喜欢

转载自blog.csdn.net/valecalida/article/details/87477638