关于python,当涉及到for循环时,它会在重新迭代之前重新评估上限吗?
假设我有以下场景:
def remove(self,list,element):
for x in range(0,len(list)):
if somecondition:
list.pop(x)
是否会在执行 for
循环的下一次迭代之前重新评估 len(list)
条件? (我相信在某些语言(如 Objective-C)中所做的)否则,如果弹出多个元素,如果删除了 1 个元素,则会出现越界错误,并且最后一次迭代将尝试访问 list [len(list)-1]
.
我曾尝试自己对此进行调查,但每次的结果都很困惑。
编辑:我相信我的问题与标记为重复的问题不同,因为我的问题是关于循环继续下一次迭代的条件,它可以很容易地添加一个元素而不是删除元素。
为了澄清,我的问题是 for 循环条件是否会重新检查下一次迭代之前提出的条件。
最佳答案
关于The for statement的文档对此很清楚:
The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object:
for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite]
The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order returned by the iterator.
[强调我的]
因此,在您的情况下,range(0,len(list))
只会计算一次。
关于python - 在 Python 中,是否在执行新迭代之前重新评估循环中的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55210200/