python-2.7 - 更新 for 循环中的 range() 函数

标签 python-2.7 iteration

我有以下伪代码。

for j in range(0, len(list)):
    xx
    xx
    if something == True:
        list.append("x")

每次 j 迭代代码块时都会调用 range(0, len(list)) ,因此其最大值会更新吗?

我尝试通过查看堆栈数据来弄清楚,但是我无法弄清楚。

最佳答案

不,因为 range(0, len(list)) 在开始时创建一次以创建列表(或 python 3 中的迭代器),然后它只是迭代(使用 next或索引)。它相当于:

list_of_nums = range(0, len(list))  # [0, 1, 2, 3, ...]
for i in list_of_nums:
    j = i[counter]
    ...

使用 while 循环,例如:

j = 0
while j < len(list)):
    xx
    xx
    if something == True:
        list.append("x")
    j += 1

关于python-2.7 - 更新 for 循环中的 range() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27333853/

相关文章:

python - 如何维护 PhotoImage 对象的多个引用

python-3.x - 如何以 float 为步长迭代整数列表?

python - 操作系统错误 : [Errno 'jupyter-notebook' not found] 2

python - 在无限循环中使用Threading和Queue不会关闭线程

java - 在Java中可以使用迭代来生成字符串吗?

java - 速度:在最后一个循环迭代中做一些事情

vbscript - VBScript 上的 "Continue"(到下一次迭代)

python "round robin"

python - 当它是 '' 时删除元组列表的元素

python - 发送 subprocess.Popen stdout, stderr 到日志记录模块