Python删除包含特定值的所有列表元素(68)
2017-08-11 本文已影响1643人
一日歌
删除列表中的元素可以使用del,pop()和remove()。具体用法如下www.jianshu.com/p/fce64120fcad
remove()一次只删除第一个指定的值。适用情况:不知道从列表中删除的值所处的位置,只知道要删除元素的值。
python大大的图

我的图

要想删除宠物列表里所有的'cat',只用一次remove是删不完的,因此必须使用循环。Python删除第一个'cat'并返回倒while代码行,然后发现'cat'还包含在列表中,因此再次进入循环。它不断删除'cat',直到这个值不再包含在列表中,然后退出循环并再次打印列表。
这种操作用for循环也可以完成

while循环比for循环简洁。while代替了for和if。
如果是增加值的话,while和if用法相似

如果在一个宠物店里,店员需要自行输入宠物形成列表,然后再对输入的宠物进行操作。第一个while循环是为了形成列表,第二个while循环是为了删除猫。

在这里append()的用法需要修改。把pets=pets.append(pet_name)改成pets.append(pet_name)就行了


我本来想在交互模式中也走一遍这个程序,我的交互模式好像中了毒:一是在语句 if pet_name == 'quit'中,两个等号会连在一起。二是一旦输入quit程序就开始发了疯一样连接不上


有没有高手能救救我的交互模式?
其实宠物店最好能够自己输入宠物列表,自己选择需要删除的宠物。可能这个程序会更好一点

