我想填充由此创建的 2D numpy 数组:
import numpy as np
arr = np.full((10,10),0)
示例坐标:
即使坐标从 2,1:2,5
切换到 2,5:2,1
或从5,1:8,1
到 8,1:5,1
如果我想在 2,1 : 2,5
上填充数据,2,1 2,2 2,3 2,4 2,5
将被填充.也与 5,1 : 5,8
最佳答案
这是一种实现方式:
import numpy as np
coords = ['2,1:2,5', '8,6:4,6', '5,1:8,1']
arr = np.full((10, 10), 0)
for coord in coords:
start, stop = map(lambda x: x.split(','), coord.split(':'))
(x0, y0), (x1, y1) = sorted([start, stop])
arr[int(y0):int(y1)+1, int(x0):int(x1)+1] = 1
这导致 arr
看起来像:
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 1, 1, 1, 1, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
关于python - 根据给定坐标填充 2D Numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58569157/