Popping items from a list using a loop

Luc*_*hns 4 python for-loop python-3.x

I am trying to write a for loop in python to pop out all the items in a list but two, so I tried this:

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")
Run Code Online (Sandbox Code Playgroud)

and this is what I get when I run it:

I am sorry joe I can no longer invite you to dinner

I am sorry frank I can no longer invite you to dinner

I am sorry mark I can no longer invite you to dinner

因此,它仅弹出3,但是否有办法使其弹出6中的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")
Run Code Online (Sandbox Code Playgroud)

我以为'phil'是1,它将弹出最后4个字符,但是当我运行该程序时,它什么也不返回。那么可以在一个for循环中做吗?

Pat*_*ugh 7

如果您想弹出4件事,那么只需数4

for _ in range(4):
    popped_guest = guest.pop()
    print("I am sorry " + popped_guest + " I can no longer invite you to dinner") 
Run Code Online (Sandbox Code Playgroud)


Rol*_*787 6

您的for循环在第 3 次迭代后停止,因为这是guest弹出前一个元素后剩余的元素数量。您可以潜在地使用 while 循环来连续弹出元素,直到列表中只剩下 2 个。

while len(guest) > 2:
    popped_guest = guest.pop()
    ...
Run Code Online (Sandbox Code Playgroud)