首页 > 解决方案 > Python递减for循环内的变量

问题描述

我将我的java代码转换为python代码以及如何减少python中for循环内的变量?如果它在 if 语句中,我尝试将索引减少 1,但显然我不能这样做。有没有其他方法可以在 for 循环中减少 i ?

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+"'");
        }

蟒蛇代码:

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

输出:好吧,如果我们查看输出,它仍然在递增而不是递减 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

标签: javapythonpython-3.x

解决方案


Python 不允许您在for循环中更改迭代器。一旦循环的下一次迭代到来,迭代器将成为可迭代对象的下一个值。

这也是因为range它的行为不像实际的类似 Java 的for循环。相反,它会不断生成范围内的数字(您可以通过list(range(10))在 Python 解释器中输入来查看这一点,它会生成一个从 0 到 9 的数字列表。

如果你想修改迭代器,你应该用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

这应该与您的 Java 代码相同,因为我只是将三个指令从 Javafor循环移动到它们的位置。不需要通知pass,因为它是无效的声明。

为了优化,我说您实际上不需要递减迭代器,只需避免递增它即可。我将此解决方案与原始答案分开,因为它与您的原始设计有很大偏差:

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

我所做的只是删除减量并将增量推到else块中,因此它仅在输入电影名称时运行。


推荐阅读