控制Python for循环的索引

控制Python for循环的索引,python,for-loop,Python,For Loop,如何控制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 收益率: 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 我希望它能产生收益: for i in range(1

如何控制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
收益率:

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
我希望它能产生收益:

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循环来控制我的索引

查看
范围
上的文档,或从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
顺便说一下,执行
i=i+1
是没有意义的,因为for循环中的每次迭代都会再次更改i。无论在循环中设置什么,都会在每次循环重新开始时被覆盖

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

不能/不应该-循环控制变量将在每次迭代结束时重新分配给下一个元素(因此
i=i+1
无效,因为
i
将在下一次迭代中重新分配给不同的元素)。如果要像那样控制索引,应使用
while
-循环:

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

看,看起来您实际上想要在列表上执行set操作。你看过集合了吗?@Chris,这在本例中并不适用,谢谢。@cmd我想一个while循环是个不错的选择。“我问这个问题的原因是,有时候我会删除person I。”所以你是从你迭代的序列中删除对象?不要那样做。建立一个新的列表,只包含你想要的。这就是我的想法。两次递增(或类似的方式)并不是我真正想要的。所以,尽管如此。谢谢我将进一步研究这个问题,然后在对解决方案有信心时接受答案。我在测试它时意识到(I=I+1是没有意义的)。我很失望。我认为一个while循环是一个不错的选择,两次递增(或者类似的方式)并不能解决我的问题。谢谢你!