为什么这个Python代码不会从列表中弹出/删除元素?

时间:2015-10-07 10:24:48

标签: python

Python代码:

PeoplesNames = []
while len(PeoplesNames) < 3:
    person = input('Enter your name: ')
    PeoplesNames.append(person)
print PeoplesNames
if 'Dan' in PeoplesNames:
    PeoplesNames.pop('Dan')
    print PeoplesNames

根据我的理解,这应该通过while循环(它执行)直到列表达到3的长度(它确实)然后打印列表(它做)然后点击if语句并从列表中删除dan然后打印新列表(它没有) 我是否需要嵌套if语句或其他内容? 感谢

2 个答案:

答案 0 :(得分:2)

list.pop() #used to pop out the top of the stack(list) or

list.pop(index) #can be an index that needed to be pop out, but

list.remove(item) # removes the item specified

尝试使用以下解决方案

if 'Dan' in PeoplesNames:
        PeoplesNames.remove('Dan')
        print PeoplesNames

答案 1 :(得分:1)

或 - 记住EAFP - 您可以:

PeoplesNames = [];
while len(PeoplesNames) < 3:
    person = raw_input('Enter your name: ')
    PeoplesNames.append(person)
print PeoplesNames
try:
    PeoplesNames.remove('Dan')
except ValueError:
    pass
print PeoplesNames

另请注意,在python 2.7中,您需要使用raw_input()代替input()