2016-07-03 70 views
-6

我想遍历一个m -by- n“棋盘”,即所有其他元素的每一个黑色的正方形,遍历一个“棋盘”

l = [] 
for i in range(m): 
    for j in range(n): 
     if (i+j) % 2 == 0: 
      l.append(something(i, j)) 

我使用的是显式循环在这里,但速度宁愿使用列表理解。

任何提示?

对于奖励积分,该解决方案也适用于i,j,k(i+j+k) % 2 == 0

+1

如果你想处理任意数量的轴,查看'itertools.product',但请注意*“任何想法?”*不是一个好的SO问题。 – jonrsharpe

回答

2

好,列表理解就像你嵌套for循环,不同之处在于,这是内做列表括号:

my_list = [something(i, j) for i in range(m) for j in range(n) if (i + j) % 2 == 0] 

更一般地,对于n嵌套循环,你可以使用itertools.product,这样:

from itertools import product 

my_list = [something(*p) for p in product(range(n), repeat=n) if sum(p) % 2 == 0] 
0

据我所知,你想在'棋盘'上的黑色方块的x和y坐标显式表达,所以你不要必须评估每个正方形的布尔值。这是我的解决方案的实现(2维板):

import numpy as np 

# 'Chess board' dimension 
m = 3  # Number of columns 
n = 4  # Number of rows 

# Counter variable. The length of this array is equal to the total number of black squares. 
k = np.arange(0,m*n,2) 

x_coords = (k + (k/n) % 2) % n  # x-coordinates of black squares 
y_coords = (k + (k/n) % 2)/n  # y-coordinates of black squares 

print("x-coordinates: "+str(x_coords)) 
print("y-coordinates: "+str(y_coords)) 

对于在上面的例子3×4维板,这会产生以下输出:

x-coordinates: [0 2 1 3 0 2] 
y-coordinates: [0 0 1 1 2 2] 

其可以验证通过绘制一个小图。请注意,'帮助变量'(k/n) % 2会记录行号是偶数还是奇数;奇数行相对于偶数行具有“偏移量”。