英文:
Nested Loop with variables
问题
我正在尝试在内部的 j 循环中打印一个值。然而,我的 j 循环不起作用。我不确定是什么原因导致它不起作用,因为我已经尝试了各种可能的方法来使它能够在 j 循环中打印值。
我该如何使这个循环正常工作?
英文:
I am trying to print a value inside the j(innermost) loop. However,my j loop is not working. I am not sure what's causing it as I tried every possible way to make it work to print values in j
loop.
How can I make the loop work ?
答案1
得分: 1
左边界始终大于右边界的内循环。您可以交换它们,或者如果您真的想要从大到小迭代,可以在 range
中使用负步骤。
现在您的步骤是正数,等于 2
。
以下是我是如何解决这个问题的:
m = 961
n = 220
for i in range(1-1, m-3):
#print ("test: i loop is working")
print((2*n*(i+5)-1), (2*n*(i+1)-5))
for j in range((2*n*(i+5)-1), (2*n*(i+1)-5), -2):
print ("test: j is not working")
输出(截断):
2639 875
3079 1315
3519 1755
3959 2195
4399 2635
4839 3075
5279 3515
5719 3955
...
英文:
Well, left border of inner loop is always greater than right one. You can either swap them or use a negative step in range
if you really want to iterate from greater to smaller.
Right now your step is positive and equals 2
.
Here's how I figured it out:
m = 961
n = 220
for i in range(2-1, m-3):
#print ("test: i loop is working")
print((2*n*(i+5)-1), (2*n*(i+1)-5))
for j in range((2*n*(i+5)-1), (2*n*(i+1)-5),2):
print ("test: j is not working")
Output (truncated):
2639 875
3079 1315
3519 1755
3959 2195
4399 2635
4839 3075
5279 3515
5719 3955
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论