从列表中删除项目是while

时间:2017-11-13 18:30:56

标签: python-3.x

有人可以帮助我理解为什么此代码在删除用户输入名称后返回列表中的原始项目而不是项目。

 lists = ['leo','bob','bob','Joe','Sam','Tracy','bob']
 counts = 0
 removeName = input(print("what name would you like to remove \n"))

 while counts != len(lists) and removeName not in lists :
     lists.remove(removeName)
     counts = counts + 1
print ("ok we removed all the", removeName, "from the list" ) 
print(lists)

1 个答案:

答案 0 :(得分:1)

使用input()函数时,无需进行打印。 Python会从您放入该参数的任何内容中找到输入,因此首先删除该打印,使其变为:

removeName = input("what name would you like to remove \n")

而不是:

removeName = input(print("what name would you like to remove \n"))

接下来,您需要记住列表中的项目是否被删除,它是一个较短的项目。这意味着如果删除某个项目,则不希望更改“计数”。最终的代码应该是:

lists = ['leo','bob','bob','Joe','Sam','Tracy','bob']
counts = 0
removeName = input("what name would you like to remove \n")
while counts != len(lists):
    if lists[counts] != removeName:
        counts = counts + 1
    else:
        lists.remove(removeName)
print ("ok we removed all the", removeName, "from the list" ) 
print(lists)