4

你如何控制python for循环的索引?(或者你可以吗?或者你应该吗?)

例如:

for i in range(10):
    print i
    i = i + 1

产量:

0
1
2
3
4
5
6
7
8
9

我希望它产生:

0
2
3
4
5
6
7
8
9
10

如果我完全偏离了这个问题,我真的很抱歉,我的大脑现在完全让我失望,解决方案很明显。


我为什么要问?

这与问题无关,但与我为什么需要答案有关。

在我正在编写的 Python 脚本中,我正在做这样的事情:

for i in persons:
    for j in persons[-1(len(persons) - i - 1:]:
        if j.name in i.name:
            #remove j.name
        else: 
            #remove i.name

    #For every person (i), iterate trough every other person (j) after person (i)
    #The reason I ask this question is because sometimes I will remove person i.
    #When that happens, the index still increases and jumps over the person after i
    #So I want to decrement the index so I don't skip over that person.

也许我的做法完全错误,也许我应该使用 while 循环并控制我的索引。

4

2 回答 2

6

How do you control the index of a python for loop? (or can you? or should you?)

You can't / shouldn't - the loop control variable will be reassigned at the end of each iteration to the next element of whatever it is you are iterating over (so that i = i + 1 has no effect, since i will be reassigned to something different for the next iteration anyway). If you want to control the index like that, you should use a while-loop:

i = 0
while i < 10:
    print i
    i = i + 1

Although, Python's range function is more flexible than you might realize. For instance, to iterate in steps of 2 you can simply use something like

for i in range(0, 10, 2):
    print i
于 2013-03-29T16:36:21.220 回答
0

查看range 此处的文档,或从 docstr:

range([start,] stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
These are exactly the valid indices for a list of 4 elements.

要获得 0-10 的范围,只需执行以下操作:

> for i in range(0, 11):
>     print i

> 0
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
> 10

By the way, it's pointless to do the i = i + 1, cause every iteration in the for loop will change i again. Whatever you set it to in the loop, will get overwritten every time the loop starts over.

于 2013-03-29T16:35:26.547 回答