2017-03-21 27 views
-4
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循環,因爲這太噁心了!我無法弄清楚如何。如何將此語句列表變爲for循環

+1

我們需要需要映射什麼的更多細節。爲什麼[0] [3]從[0] [0]分配? – languitar

+0

請爲您的問題添加一些更多詳細信息。解釋爲什麼要選擇inp [0] [0] = shadow [3] [0]而不是inp [0] [0] = shadow [0] [0] – Ashish

回答

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] 

通過賦予的-1enumerate() function起點,我們創建了一個偏移量將在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]