说我有以下情况:
def remove(self,list,element): for x in range(0,len(list)): if somecondition: list.pop(x)
在执行for循环的下一次迭代之前,是否会重新评估len(list)条件? (正如在某些语言中所做的那样,例如Objective-C我相信)如果弹出了许多元素,如果说删除1个元素,则会出现越界错误,最后一次迭代会尝试访问列表[len(列表)-1].
我自己试图对此进行调查,但每次结果都很混乱.
编辑:我认为我的问题与标记为重复的问题不同,因为我的问题是关于循环继续下一次迭代的条件,它可以很容易地添加元素而不是删除元素.
为了澄清,我的问题是询问for循环条件是否会重新检查下一次迭代之前提出的条件.
解决方法
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(列表))将仅评估一次.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。