在 Python 中更改 for 循环内的迭代变量 [英] Changing iteration variable inside for loop in Python

查看:64
本文介绍了在 Python 中更改 for 循环内的迭代变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些简单的事情,例如更改我正在迭代的变量 (i),但我在 Python 和 C 中得到了不同的行为.

I am trying to do something as simple as changing the varible in which I am iterating over (i) but I am getting different behaviours in both Python and C.

在 Python 中,

In Python,

for i in range(10):
    print i,
    if i == 2:
        i = 4;

我得到 0 1 2 3 4 5 6 7 8 9,但在 C 中是等价的:

I get 0 1 2 3 4 5 6 7 8 9, but the equivalent in C:

int i;
for (i = 0; i < 10; i++) {
    printf("%d", i);
    if (i == 2)
        i = 4;
}

我收到 01256789(请注意,数字 3 和 4 没有按预期出现).

I get 01256789 (note that numbers 3 and 4 don't appear, as expected).

这里发生了什么?

推荐答案

你没有按照自己的想法去做.
例如:

You are not doing what you think you are.
For example:

for i in range(10):

无论如何都会不断地将 i 设置为 0-10 范围内的下一个元素.

will constantly set i to be the next element in the range 0-10 no matter what.

如果你想在 python 中做同样的事情,你会这样做:

If you want to do the equivalent in python you would do:

i = 0
while i < 10:
    print(i)
    if i == 2:
        i = 4
    else:      # these line are
        i += 1 # the correct way
    i += 1 # note that this is wrong if you want 1,2,4,5,6,7,8,9

如果您尝试将其转换为 C,那么您必须记住 for 循环中的 i++ 将始终添加到i.

If you are trying to convert it to C then you have to remember that the i++ in the for loop will always add to the i.

这篇关于在 Python 中更改 for 循环内的迭代变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆