本文介绍了有没有更有效的方法从另一个数组生成一个带有一些复杂规则的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算元素与数组中起点之间的距离.

I am trying to compute a distance between an element and a starting point in an array.

这是一个数组

假设元素(0,1)是当前值最高的起点.

assume the element (0,1) is a starting point which has the highest value currently.

如果邻居具有一个共同点,并且在另一个轴上相差1个单位,则邻居是围绕特定点的元素.

a neighbors is an element around a specific point if they have one axis in common and different in another axis by 1 unit.

通常,邻居可以是数组内部特定点的顶部,底部,左侧,右侧.

generally, a neighbor could be the top, bottom, left, right of a specific point, which is inside the array.

任务是用距离值标记每个元素,该距离值指示距起点(0,1)的距离.

the task is to label every elements with a distance value indicate how far it is from the starting point (0,1).

ds = np.array([[1, 2, 1],
       [1, 1, 0],
       [0, 1, 1]])

dist = np.full_like(ds, -1)
p0 = np.where(ds == 2)
dist[p0] = 0
que = []
que.append(p0)
nghb_x = [0, 0, -1, 1]
nghb_y = [-1, 1, 0, 0]

while len(que):
    x, y = que.pop()
    d = dist[(x,y)]
    for idx0, idx1 in zip(nghb_x, nghb_y):
        tmp_x = x + idx0
        tmp_y = y + idx1
        if np.any(tmp_x >= 0) and np.any(tmp_x < ds.shape[0]) and np.any(tmp_y >= 0) and np.any(tmp_y < ds.shape[1]) and np.any(dist[(tmp_x,tmp_y)] == -1):
            dist[(tmp_x,tmp_y)] = d + 1 # distance = distance(x) + 1
            que.append((tmp_x, tmp_y))

print('dist:')
print(dist)

输出

dist:
[[1 0 1]
 [2 1 2]
 [3 2 3]]

是如预期的那样,我想知道是否有更有效的方法来做到这一点?

is as expected though, I would like to know if is there a more efficient way to do this?

推荐答案

您正在计算曼哈顿距离(每个点距目标点的x距离和y距离).

You're calculating the Manhattan distance (the x-distance plus the y-distance) from a target point for each point.

在给出目标坐标和数组形状的情况下,您可以使用numpy函数一步完成此操作:

You can use a numpy function to do it in one step, given the target coordinates and the shape of the array:

target = (0, 1)
np.fromfunction(lambda x,y: np.abs(target[0]-x) + np.abs(target[1]-y), ds.shape)    

结果:

[[1. 0. 1.]
 [2. 1. 2.]
 [3. 2. 3.]]

演示: https://repl.it/repls/TrustyUnhappyFlashdrives

这篇关于有没有更有效的方法从另一个数组生成一个带有一些复杂规则的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 03:47