【发布时间】:2023-03-14 14:36:01
【问题描述】:
此代码是在 Jupyter Notebooks 中用 Python 3.6 编写的。在其他语言中,我很确定我构建了如下所示的循环:
endRw=5
lenDF=100 # 1160
for i in range(0, lenDF):
print("i: ", i)
endIndx = i + endRw
if endIndx > lenDF:
endIndx = lenDF
print("Range to use: ", i, ":", endIndx)
# this line is a mockup for an index that is built and used
# in the real code to do something to a pandas DF
i = endIndx
print("i at end of loop", i)
但在测试中,i 不会重置为 endIndx,因此循环不会构建预期的索引值。
我能够通过构建这样的 while 循环来解决这个问题并得到我想要的:
endRw=5
lenDF=97 # 1160
i = 0
while i < lenDF:
print("i: ", i)
endIndx = i + endRw
if endIndx > lenDF:
endIndx = lenDF
print("Range to use: ", i, ":", endIndx)
# this line is a mockup for an index that is built and used
# in the real code to do something to a pandas DF
i = endIndx
print("i at end of loop: ", i)
问题:有没有办法从 python 中的for 循环内部修改i?有没有办法在 Python 中使用 for 循环来完成我对 while 循环所做的事情?
用while 解决了这个问题,但只是对此感到好奇。
【问题讨论】:
-
你没有明确你的目标到底是什么。如果您只想结束整个循环,请使用
break。 -
@KlausD。 - 我的测试循环的输出有点长,但是如果您在 Python 中运行 while 循环,目标是获得与 while 循环生成的输出相同的输出,但使用 for 循环进行。更具体地说,我最初遇到了麻烦,因为我在其他语言中修改了 for 循环中的 i 变量,就像我在所示的 for 循环中尝试的方式一样,但它在 Python 中不起作用,我在这里看到了一些很好的答案为什么我将不得不进行一些测试,以确定哪个最接近我认为的目标。
-
@TMWP 刚刚看到您对我的回答的编辑被拒绝。你为什么不把它作为一个单独的答案呢?我认为这是值得的。
-
@PaulPanzer 它采用了您向我展示的概念并将它们集成到原始代码中,以便它们工作。在这方面,它对我来说并不是一个新的答案,而是一个更完整的答案。此外,以我的拙见借用您的概念的答案不应与您的答案竞争。如果您现在无法取消或接受我上一次被拒绝的编辑,但喜欢这个想法,请告诉我,我会再次编辑,以便您接受。
-
@PaulPanzer 如果在阅读了我之前的评论后,您仍然认为它需要作为新答案发布,请告诉我,我可能会这样做。我只是喜欢添加到您的完整性的想法。