我试着在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")
这就是我运行它时得到的结果:
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")
我本来以为,因为'菲尔'将是1,它会弹出最后4,但当我运行的程序,它返回什么。那么,有没有可能在一个for循环中执行?
8条答案
按热度按时间ve7v8dk21#
如果你想弹出4个东西,那就数到4
yiytaume2#
for
循环在第三次迭代后停止,因为这是弹出前一个元素后guest
中剩余的元素数。您可以使用while循环来连续弹出元素,直到列表中只剩下2个元素。lstz6jyr3#
如前所述,您的代码根本没有做您认为它是什么,因为您正在从列表中弹出元素,同时积极地迭代它。我会说“一个更好的编码实践是复制要弹出的列表”,但这不是一个“更好”的实践-你的方式根本不像你想要的那样工作,它总是弹出列表的前半部分。
我会问自己“我如何指定在我当前的迭代中弹出的人”,以及“我在哪里设置在我当前的迭代中弹出的人的数量”。这两个问题的答案似乎都是“我不知道”。
lymnna714#
这种行为的原因是,当你在Python中使用for循环时,它实际上是通过它的索引号遍历列表。因此,当你在一个列表上循环并同时改变它时,你可能会跳过一些元素。更好的方法是在循环原始列表的同时改变列表的副本。
cfh9epnr5#
9rnv2umw6#
让2个值仍然在列表中。而当列表长度未知时。
6qftjkof7#
您可以将
list()
和copy()
用于numbers
,以创建不同的复制numbers
,如下所示:或者:
输出:
tjrkku2a8#
我添加了一些代码,希望它可以帮助你。