如何将这个语句列表转换为for循环

时间:2017-03-21 11:02:08

标签: python for-loop

inp[0][0] = shadow[3][0]
inp[0][3] = shadow[0][0]
inp[3][3] = shadow[0][3]
inp[3][0] = shadow[3][3]

我想将此代码转换为for循环,因为这很恶心!我无法弄清楚如何。

1 个答案:

答案 0 :(得分:0)

您基本上是以环形方式从系列(0, 0), (0, 3), (3, 3), (3, 0)中挑选两组坐标。您可以通过对该系列进行迭代来实现,其中索引用于第二点:

points = [(0, 0), (0, 3), (3, 3), (3, 0)]
for index, (x, y) in enumerate(points, -1):
    shadow_x, shadow_y = points[index]
    inp[x][y] = shadow[shadow_x][shadow_y]

通过将enumerate() function作为-1的起点,我们会创建一个偏移量,以便在points中找到正确的匹配点。

您也可以使用zip() function

points = [(0, 0), (0, 3), (3, 3), (3, 0)]
for (x, y), (shadow_x, shadow_y) in zip(points, [points[-1]] + points):
    inp[x][y] = shadow[shadow_x][shadow_y]

选择最适合您用途的产品。

演示(用print()语句替换实际作业,以显示将要执行的内容):

>>> points = [(0, 0), (0, 3), (3, 3), (3, 0)]
>>> for index, (x, y) in enumerate(points, -1):
...     shadow_x, shadow_y = points[index]
...     print(f"inp[{x}][{y}] = shadow[{shadow_x}][{shadow_y}]")
...
inp[0][0] = shadow[3][0]
inp[0][3] = shadow[0][0]
inp[3][3] = shadow[0][3]
inp[3][0] = shadow[3][3]
>>> for (x, y), (shadow_x, shadow_y) in zip(points, [points[-1]] + points):
...     print(f"inp[{x}][{y}] = shadow[{shadow_x}][{shadow_y}]")
...
inp[0][0] = shadow[3][0]
inp[0][3] = shadow[0][0]
inp[3][3] = shadow[0][3]
inp[3][0] = shadow[3][3]