英文:
How do reverse the indexing order of a sub-loop every other pass?
问题
我有一个表示x和y位置的二维数组(10x10)。我正在编写一个脚本,它会遍历每个位置,做一些操作,然后移动到下一个位置。
最有效的方法是从一个角开始,以恒定的x值扫描(移动通过y值),然后在所有y值的末尾,移动到下一个x值,并以相反的顺序移动通过y值。有点像蛇形图案,如果这样说得通的话。
我的循环目前看起来像这样:
for x in x_values:
for y in y_values:
做一些操作()
移动到 y + 1
移动到 x + 1
回到第一个y值
正如你所看到的,我正在完成一列(在y上),前进一个x值,然后倒回到第一个y值。对于偶数x值,我想以相反的顺序运行y值。
最简单的方法是什么?
英文:
I have a 2 dimensional array (10x10) that represents x & y positions. I'm writing a script that goes to each position, does some stuff, then moves to the next position.
The most efficient way would be to start in one corner, scan at a constant x value (moving through y values), then at the end of all of the y values, moves over one x value and moves through y values in reverse order. Kind of like a snake pattern if that makes sense.
My loop currently looks something like this:
for x in x_values:
for y in y_values:
do_something()
move to y + 1
move to x + 1
move back to first y value
As you can see, I'm completing a column (in y), advancing one x value, then rewinding back to the first y value. I'd like to run the y values in reverse for even number x values.
What is the simplest way to do this?
答案1
得分: 3
这应该解决你的问题
对于 x_values 中的每个 x:
对于 y_values 中的每个 y:
做一些操作()
反转 y_values
在对 y_values
的每次迭代之后,都会反转 y_values
。
英文:
This should solve your problem
for x in x_values:
for y in y_values:
do_something()
y_values.reverse()
After each iteration over y_values
, y_values
is reversed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论