我有以下细胞:
cells = np.array([[1, 1, 1],
[1, 1, 0],
[1, 0, 0],
[1, 0, 1],
[1, 0, 0],
[1, 1, 1]])
Run Code Online (Sandbox Code Playgroud)
我想计算水平和垂直邻接以获得这个结果:
# horizontal adjacency
array([[3, 2, 1],
[2, 1, 0],
[1, 0, 0],
[1, 0, 1],
[1, 0, 0],
[3, 2, 1]])
# vertical adjacency
array([[6, 2, 1],
[5, 1, 0],
[4, 0, 0],
[3, 0, 1],
[2, 0, 0],
[1, 1, 1]])
Run Code Online (Sandbox Code Playgroud)
实际的解决方案如下所示:
def get_horizontal_adjacency(cells):
adjacency_horizontal = np.zeros(cells.shape, dtype=int)
for y in range(cells.shape[0]):
span = 0
for x …Run Code Online (Sandbox Code Playgroud) 到目前为止,我的 for 循环虽然使用了向量,但工作正常:
foo = c("one","two","three")
for (bar in 1:length(foo)) {
print(bar)
}
#[1] 1
#[1] 2
#[1] 3
Run Code Online (Sandbox Code Playgroud)
但是,我注意到即使向量为空也会访问循环:
foo = c()
for (bar in 1:length(foo)) {
print(bar)
}
#[1] 1
#[1] 0
Run Code Online (Sandbox Code Playgroud)
当然,我可以使用 IF 语句(if (length(foo)!=0)),但我确信有更好的方法来做到这一点。
也许我有一个过于“pythonic”的策略,因为在那里我不会有问题
foo = []
for bar in foo:
print(bar)
Run Code Online (Sandbox Code Playgroud)
如果我的向量为空,防止访问 for 循环的最佳方法是什么?