说我有以下情况:
def remove(self,List,element): for x in range(0,len(List)): if somecondition: List.pop(x)
在执行for循环的下一次迭代之前,是否会重新评估len(List)条件? (正如在某些语言中所做的那样,例如Objective-C我相信)如果d出了许多元素,如果说删除1个元素,则会出现越界错误,最后一次迭代会尝试访问列表[len(列表)-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.
[强调我的]
因此,在您的情况下,范围(0,len(列表))将仅评估一次.
总结以上是内存溢出为你收集整理的在Python中,是否在执行新迭代之前重新评估循环中的条件?全部内容,希望文章能够帮你解决在Python中,是否在执行新迭代之前重新评估循环中的条件?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)