Python:为什么 for 循环的行为很奇怪?

标签 python python-3.x

我只是想将两个排序列表合并为一个排序列表。我知道这是一项简单的任务并且在线有很多解决方案,但我的问题是不同的。这是我的代码:

def merge(list1, list2):
    len1 = len(list1)
    len2 = len(list2)

    list3 = []
    pointer = 0

    for i in range(len1):
        if (list1[i] >= list2[pointer]):
            while (pointer < len2 and list1[i] >= list2[pointer]):
                list3.append(list2[pointer])
                pointer += 1
            i -= 1
        else:
            list3.append(list1[i])

    while (pointer < len2):
        list3.append(list2[pointer])
        pointer += 1

    return list3


if __name__ == "__main__":
    print(merge([1, 2, 3, 10, 11, 22], [4, 5, 6, 7, 20, 21, 30]))

我进行了调试,我很困惑地看到当我将值 i 减少 1 时,例如从 3 到 2,在下一次迭代中它又回到 4。我不知道为什么?您可以通过运行代码并查看结果来检查它。我只需要解释为什么会这样。谢谢

最佳答案

I was confused to see that when I decrease the value i by 1, for example from 3 to 2, on the next iteration it goes back to 4. I have no idea why?

因为 for i in range(x)意思是“执行 for 体与 i 假设值 0 到 x-1”。为 i 分配不同的值不影响其在下一次迭代中的值。

换句话说,for i in range(10) 不是 C 或 JavaScript 的 for (i = 0; i < 10; i++) 的翻译.相反,您可以将其视为 for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] .这样看,很明显改变一个值 i不会影响后续值,这是盲目地从预先生成的列表中取出的。如果需要根据变化的条件修改迭代进度,可以显式编写C/JS风格的循环:

i = 0
while i < len1:
   # ... loop body goes here ...
   i += 1

这样写,修改i in 循环体将以您预期的方式影响迭代。

关于Python:为什么 for 循环的行为很奇怪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58471951/

相关文章:

python - 在 Python 中处理大文件的最快方法

postgresql - psycopg 错误,列不存在

python - 我正在尝试制作一个使您失去 "energy"的程序(Python 3)

Python多处理存储数据直到在每个进程中进一步调用

python - 如何用python中的函数改变列表?

python - 可以在 Python 3.7 的内置正则表达式中使用 Unicode block (\p{InBasic_Latin}) 来匹配规范等效项

python - 搁置:无法pickle <class 'method' >:属性查找builtins.method失败

python - multiprocessing.Queue 是否与 gevent 一起工作?

python - 打开(文件名,模式)Python

python - "TypeError: a bytes-like object is required, not ' str '"在Python 3中处理文件内容时