如何解决Python while循环问题?

时间:2020-04-12 05:58:46

标签: python while-loop

运行此代码

letters=["cat","dog","3","gorilla","cat","cat","cat"]
while True:
    if(letters[0:7].__eq__("cat")):
        letters.remove("cat")
        print(letters)

我收到此错误

['dog', '3', 'gorilla', 'cat', 'cat', 'cat'] ['dog', '3', 'gorilla', 'cat', 'cat'] ['dog', '3', 'gorilla', 'cat'] ['dog', '3', 'gorilla']
Traceback (most recent call last): File "C:/Users/HARISH G/PycharmProjects/projects/one.py", line 4, in <module> letters.remove("cat")
ValueError: list.remove(x): x not in list

您能帮助我理解原因吗?

2 个答案:

答案 0 :(得分:1)

也许,请尝试一种好的循环形式:

letters=["cat","dog","3","gorilla","cat","cat","cat"]
print(letters)
while "cat" in letters:
    letters.remove("cat")
    print(letters)
print("Removed All cats one by one")

答案 1 :(得分:1)

使用while循环,直到列表中cat的数量不为0

letters=["cat","dog","3","gorilla","cat","cat","cat"]
while (letters.count("cat")):  # looping till all cat's are removed 
    letters.remove("cat") 
print(letters)