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

2024-04-25 06:51:07 发布

您现在位置: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语句还是其他什么? 谢谢


Tags: 代码name列表inputyourlenif语句
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

或者——记住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()。你知道吗

相关问题 更多 >