Control the index of a Python for loop
如何控制python for循环的索引?(或者你能吗?)或者你应该?)
例如:
1 2 3 | for i in range(10): print i i = i + 1 |
产量:
1 2 3 4 5 6 7 8 9 10 | 0 1 2 3 4 5 6 7 8 9 |
我想让它屈服:
1 2 3 4 5 6 7 8 9 10 | 0 2 3 4 5 6 7 8 9 10 |
我真的很抱歉,如果我完全偏离了这个问题的轨道,我的大脑现在完全失去了我的能力,而且解决办法是显而易见的。
我为什么要问?
这与问题无关,但与我为什么需要答案有关。
在我正在编写的python脚本中,我正在执行如下操作:
1 2 3 4 5 6 7 8 9 10 11 | 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循环来控制我的索引。
How do you control the index of a python for loop? (or can you? or should you?)
您不能/不应该-循环控制变量将在每次迭代结束时重新分配给正在迭代的下一个元素(这样,
1 2 3 4 | i = 0 while i < 10: print i i = i + 1 |
尽管如此,python的
1 2 | for i in range(0, 10, 2): print i |
在这里或从docstr查看
1 2 3 4 5 6 7 | 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的范围,只需执行以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | > for i in range(0, 11): > print i > 0 > 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > 9 > 10 |
顺便说一下,执行