简体   繁体   English

Python递减for循环内的变量

[英]Python decrement the variable inside for loop

i converted my java code into a python code and how to decrement the variable inside of the for loop in the python?我将我的 java 代码转换为 python 代码,以及如何在 python 中减少 for 循环内的变量? I try to decrease the index by 1 if it is inside the if statement, but apparently I can't do that.如果它在 if 语句中,我尝试将索引减少 1,但显然我不能这样做。 Is there any other way that I can decrease i in a for loop?有没有其他方法可以在 for 循环中减少 i ?

Java Code: Java代码:

for(int i = 1; i <= 3; i++)
        {
            System.out.print("Enter Movie " + i + " of " + 3 + " : ");
            String inputMovie = sc.nextLine();
            if (inputMovie.equals("")) 
            {
                System.out.println("Please input a movie name.");
                System.out.println("");
                i--;
            }

            else
                movies.offer("'"+inputMovie+"'");
        }

Python Code:蟒蛇代码:

for i in range(1,4):
    inputMovie=input("Enter Movie " + str(i) + " of " + str(3) + " : ")
    if inputMovie=="":
        print("Please input a movie name")
        print("")
        i-=1
        pass
    else:
        movies.append(inputMovie)
    pass

Output: well if we look at the output it is still incrementing not decrementing the i输出:好吧,如果我们查看输出,它仍然在递增而不是递减 i

Enter Movie 1 of 3 :
Please input a movie name

Enter Movie 2 of 3 :
Please input a movie name

Enter Movie 3 of 3 :
Please input a movie name

Python doesn't let you alter the iterator in a for loop. Python 不允许您在for循环中更改迭代器。 As soon as the next iteration of the loop comes by, the iterator will be the next value of the iterable.一旦循环的下一次迭代到来,迭代器就会成为可迭代对象的下一个值。

This is also because range doesn't behave like an actual Java-like for loop.这也是因为range行为不像真正的 Java 类for循环。 Instead, it keeps generating numbers within the range (you can see this by typing list(range(10)) in a Python interpreter, it will make a list of numbers from 0 to 9.相反,它会不断生成范围内的数字(您可以通过在 Python 解释器中键入list(range(10))来查看这一点,它将生成一个从 0 到 9 的数字列表。

If you want to modify the iterator, you should go old-school with a while loop instead:如果你想修改迭代器,你应该使用while循环来代替:

i = 1
while i <= 3:
    inputMovie=input("Enter Movie " + str(i) + " of " + str(3) + " : ")
    if inputMovie=="":
        print("Please input a movie name")
        print("")
        i-=1
    else:
        movies.append(inputMovie)
    i = i + 1

This should do the same as your Java code, as I'm just moving the three instructions from the Java for loop to their places.这应该与您的 Java 代码相同,因为我只是将三个指令从 Java for循环移动到它们的位置。 Notice pass is not required as it is a statement with no effect.不需要通知pass因为它是一个没有效果的声明。

For the sake of optimization, let me say you don't really need to decrement the iterator, just avoid incrementing it instead.为了优化,让我说你真的不需要减少迭代器,只是避免增加它 I keep this solution separate from the original answer since it is a significant deviation from your original design:我将此解决方案与原始答案分开,因为它与您的原始设计存在重大偏差:

i = 1
while i <= 3:
    inputMovie=input("Enter Movie " + str(i) + " of " + str(3) + " : ")
    if inputMovie=="":
        print("Please input a movie name")
        print("")
    else:
        movies.append(inputMovie)
        i = i + 1

All I've done is remove the decrement and push the increment to the else block so it is only run if a movie name has been input.我所做的就是删除减量并将增量推送到else块,因此它仅在输入电影名称时运行。

you should use a while statement你应该使用while语句

"Unfortunately" the for loop will keep "memory" and reassign to the next value at each iteration “不幸的是” for循环将保留“内存”并在每次迭代时重新分配给下一个值

i = 1
while i < 4:
    inputMovie = input("Enter Movie " + str(i) + " of " + str(3) + " : ")
    if inputMovie == "":
        print("Please input a movie name")
        print("")
        i-=1
    else:
        movies.append(inputMovie)
        i+=1

the pass instruction is irrelevant, you can omit that pass指令无关紧要,你可以省略

pass statement通过语句

range(low,high) generates a sequence consisting of elements starting from low and ending at high-1 . range(low,high)生成一个由从low开始到high-1结束的元素组成的序列。 That's why your i-=1 doesn't work, since I is iterating in that list.这就是为什么您的i-=1不起作用,因为我正在该列表中进行迭代。
The easiest alternative here would be to use a while loop.这里最简单的替代方法是使用while循环。

while i<target:
    if something:
        #do something
        i += 1

The for loop in Python is more like for-each. Python 中的 for 循环更像是 for-each。 So the loop value(i) will get updated to the next value regardless of the changes/updates in the loop.因此,无论循环中的更改/更新如何,循环值(i)都将更新为下一个值。

A better way to do this would be to use a while loop.更好的方法是使用 while 循环。

i = 1
while i <= 3:
    inputMovie = input("Enter Movie " + str(i) + " of " + str(3) + " : ")
    if inputMovie=="":
        print("Please input a movie name")
        print("")
        i-=1
        pass
    else:
        movies.append(inputMovie)
        i+=1
    pass

You have to set your range() function correctly.您必须正确设置range()函数。 In order to decrement the loop you can use while loop or you can change your algorithm and set the for loop but now what you can do is if you can select the range functions step value to -1.为了减少循环,您可以使用while循环,或者您可以更改算法并设置for循环,但现在您可以做的是将范围函数步长值选择为 -1。 Please try it to check the code coz i also have the same question in mind like you.请尝试检查代码,因为我也和你一样有同样的问题。

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

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