【发布时间】:2013-03-20 09:31:02
【问题描述】:
如何控制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 循环并控制我的索引。
【问题讨论】:
-
看起来您实际上想要对列表进行设置操作。你看过布景吗?
-
@Chris 这在这种情况下并不适用,谢谢。
-
@cmd 我认为 while 循环将是可行的方法。
-
"我问这个问题的原因是因为有时我会删除人 i。"所以你要从你正在迭代的序列中删除对象?不要那样做。建立一个只包含您想要的列表的新列表。