简体   繁体   English

for 循环中的计数器没有变化

[英]The counter in the for loop doesn't get change

when I put i=x in the given code, the i in the for loop doesn't get change.当我在给定的代码中放入 i=x 时,for 循环中的 i 不会改变。

s=input()
d={}
Str=""
for i in range(len(s)):
    if s[i] not in d:
        d[s[i]]=i
    else:
        x=d[s[i]]
        res=str("".join(d.keys()))
        if len(Str)<len(res):
            Str=res
        i=x
        d.clear()
print(Str)

The counter, i, does get changed to x, but only for a brief instance.计数器 i 确实更改为 x,但仅用于一个简短的实例。 Think of for i in range(n) being implemented like:想想for i in range(n)被实现如下:

i = first value in range
while True:
    do something;
    i=x; # your assignment
    if no more values in range:
        break;
    else:
        i = next value in range;

So right after you assign x to i, you ultimately reach the bottom of the for loop and assign to i the next value in the range expression.因此,在将 x 分配给 i 之后,您最终会到达for循环的底部并将范围表达式中的下一个值分配给 i。

The above is not exactly how range is implemented, but you get the idea.以上并不是range的具体实现方式,但您明白了。 You are expecting it to behave more like:您期望它的行为更像:

i = 0
while i < n:
    do something;
    i = x;
    i += 1

You could implement your loop that way.你可以这样实现你的循环。

i是计数器,所以如果你将它设置为循环内的一个值,它就不会正确计数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM