java - 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
解决方案
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
块中,因此它仅在输入电影名称时运行。
推荐阅读
- html - WebStorm - 实时模板 - Twig + Html 不起作用
- reactjs - 如何删除 React Navigation 5 中每个选项卡屏幕的标题?
- kubernetes - 微服务 API 网关和 Identity Server 4 kubernates
- php - localhost:xxxx 数据库连接更改为 TCP/IP?
- reactjs - React Hook 函数 useEffect
- mysql - 查询列出与指定用户回答类似问题的用户
- angular - 在检查要在单元测试中定义的 gridOptions.api 后触发 onGridReady 事件时,gridOptions.api 为 null
- java - Java 2D 旋转 BufferedImage
- javascript - D3 GeoJSON 仅在矩形中渲染部分地图
- python - 如何让我的屏幕在 pygame 中放大和缩小?