如何在Python3中手动处理迭代器变量



我想知道如何在Python3中手动处理迭代器变量。例如,在C中,如果在for循环期间,例如:

for( int i = 0, k = 10; i < k; ++i),当i == {2,3,4}时,我可以跳过循环迭代,只需在循环体中设置i,如下所示:if(i == 1) i = 5;

然而,当我在Python3中的for in循环中执行类似的操作时,for in循环实际上强制我不能执行此操作——它会对i进行变异,并将其设置为下一个序列号,而不管我对循环体中的迭代器变量做了什么。

例如,在下面的Python3代码中,我试图将i推进到j的位置,这样,一旦算法检测到一组空间,我就可以跳过i到该组空间的末尾:

testString = "This is a   testzstring"
# find length and end of each space group
spacePositionsAndLengths = {}
j = 0
length = len(testString)
for i in range(length):
if testString[i] == " ":
j = i # mark beginning of spaces
while j < length and testString[j] == " ":
j += 1
# j-1 is now the last space. Alternatively, j is at first non-space
lengthOfSpaces = j-i
print(f"i: {i}t lengthOfSpaces: {lengthOfSpaces}")
spacePositionsAndLengths[i] = lengthOfSpaces
i = j # remember, at this point j is at first non-space
print(testString)

该算法在使用运行时打印此输出

i: 4     lengthOfSpaces: 1
i: 7     lengthOfSpaces: 1
i: 9     lengthOfSpaces: 3
i: 10    lengthOfSpaces: 2
i: 11    lengthOfSpaces: 1
This is a   testzstring

这是体面的,但我想要的是它打印这个:

i: 4     lengthOfSpaces: 1
i: 7     lengthOfSpaces: 1
i: 9     lengthOfSpaces: 3
This is a   testzstring

我不想要多余的3..2..1";倒计时";样式空间计数。

注意:我不是在构建生产应用程序;我正在研究算法,指令要求我不要使用许多内置的字符串方法。我注意到这一点是因为我期待评论说";为什么不使用X、Y或Z内置函数,并在一行中完成整个操作">

要手动推进迭代器,您需要访问它。您可以自己显式创建迭代器并将其提供给for语句,然后根据自己的意愿进行处理。示例:

irange = iter(range(10))
for i in irange:
print(i)
next(irange)

输出:

0
2
4
6
8

尽管在您的示例中,while循环可能会更好。

您需要的是一个while循环,这样您就可以拥有自己的迭代器,可以对其进行变异。它可能看起来像。

j = 0
i = 0
length = len(testString)
while i < length:
if testString[i] == " ":
j = i # mark beginning of spaces
while j < length and testString[j] == " ":
j += 1
# j-1 is now the last space. Alternatively, j is at first non-space
lengthOfSpaces = j-i
print(f"i: {i}t lengthOfSpaces: {lengthOfSpaces}")
spacePositionsAndLengths[i] = lengthOfSpaces
i = j # remember, at this point j is at first non-space
i += 1

最新更新