我试图在python中编写一个for循环来弹出列表中的所有项目但是两个,所以我尝试了这个:
guest = ['john', 'phil', 'andy', 'mark', 'frank', 'joe']
for people in guest:
popped_guest = guest.pop()
print("I am sorry " + popped_guest + " I can no longer invite you to dinner")
这就是我运行它时得到的结果:
我很抱歉,我不能再邀请你去吃饭了
我很抱歉坦白说我再也不能邀请你去吃饭了
对不起,我不能再邀请你去吃饭了
所以它只会弹出3但有没有办法让它弹出4中的4个?我尝试添加一个if语句:
guest = ['john', 'phil', 'andy', 'mark', 'frank', 'joe']
for people in guest:
if people > guest[1]:
popped_guest = guest.pop()
print("I am sorry " + popped_guest + " I can no longer invite you to dinner")
我会想到,因为'phil'将是1,它会弹出最后4个但是当我运行程序时它什么也没有返回。那么有可能在一个for循环中做?
如果你想要弹出4件事,那么只需要数到4
for _ in range(4):
popped_guest = guest.pop()
print("I am sorry " + popped_guest + " I can no longer invite you to dinner")
你的for
循环在第3次迭代后停止,因为在弹出之前的guest
之后剩下多少元素。你可以使用while循环连续弹出元素,直到列表只剩下2。
while len(guest) > 2:
popped_guest = guest.pop()
...
如前所述,您的代码完全没有按照您的想法进行操作,因为您正在积极地迭代它,从而将元素从列表中弹出。我会说“一个更好的编码实践就是复制列表以便弹出”,但这不是一个“更好”的练习 - 你的方式根本不能按照你想要的方式工作,它总会弹出列表的前半部分。
我会问自己“如何指定在当前迭代中弹出的人”,以及“我在哪里设置当前迭代中弹出的人数”。这两个问题的答案似乎是“我没有”。
这种行为的原因是,当您在Python中使用for循环时,它实际上通过其索引号浏览列表。因此,当您循环遍历列表并同时对其进行变更时,可能会跳过一些元素。更好的方法是在循环原始列表的同时改变列表的副本。
invite = ['Pankaj', 'Deepak', 'Nischey', 'Ram', 'Martin', 'Gopal']
for item in invite:
if invite.index(item) > 1:
popped_guest = invite.pop()
print("Sorry you are not invited " + popped_guest)
else:
print("you are invited " + item)