加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在Python中,是否在执行新迭代之前重新评估循环中的条件?

发布时间:2020-12-20 11:10:09 所属栏目:Python 来源:网络整理
导读:至于 python,当涉及到for循环时,它会在重新迭代之前重新计算上限吗? 说我有以下情况: def remove(self,list,element): for x in range(0,len(list)): if somecondition: list.pop(x) 在执行for循环的下一次迭代之前,是否会重新评估len(list)条件? (正如在
至于 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个元素,则会出现越界错误,最后一次迭代会尝试访问列表[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(列表))将仅评估一次.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读