xx和yy对应于9个矩形的顶点。 如何获得每个矩形的4个坐标作为元组?
>>> import numpy as np
>>> xx, yy = np.mgrid[0:4, 10:14]
>>> xx
array([[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])
>>> yy
array([[10, 11, 12, 13],
[10, 11, 12, 13],
[10, 11, 12, 13],
[10, 11, 12, 13]])
>>> xx, yy = xx.ravel(), yy.ravel()
>>> xx
array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3])
>>> yy
array([10, 11, 12, 13, 10, 11, 12, 13, 10, 11, 12, 13, 10, 11, 12, 13])
>>> lists = list(zip(xx, yy))
>>> lists
[(0, 10), (0, 11), (0, 12), (0, 13), (1, 10), (1, 11), (1, 12), (1, 13), (2, 10), (2, 11), (2, 12), (2, 13), (3, 10), (3, 11), (3, 12), (3, 13)]
第一个矩形的坐标为:
[(0, 10), (0, 11), (1, 11), (1, 10)].
同样,我想以“列表列表”的格式获取其他8个矩形的坐标。
矩形坐标的顺序并不重要。
NumPy / SciPy方法优先。
答案 0 :(得分:2)
单向,不使用mgrid
:
x = np.arange(4)
y = np.arange(10, 14)
d = [[0,0],[0,1],[1,1],[1,0]] # define order to go around rectangle here
for ix in range(len(x) - 1):
for iy in range(len(y) - 1):
print [(x[ix + dx], y[iy + dy]) for dx, dy in d]
结果:
[(0, 10), (0, 11), (1, 11), (1, 10)]
[(0, 11), (0, 12), (1, 12), (1, 11)]
[(0, 12), (0, 13), (1, 13), (1, 12)]
[(1, 10), (1, 11), (2, 11), (2, 10)]
[(1, 11), (1, 12), (2, 12), (2, 11)]
[(1, 12), (1, 13), (2, 13), (2, 12)]
[(2, 10), (2, 11), (3, 11), (3, 10)]
[(2, 11), (2, 12), (3, 12), (3, 11)]
[(2, 12), (2, 13), (3, 13), (3, 12)]
如果你坚持只使用numpy,你可以这样做:
xx, yy = np.mgrid[0:4, 10:14]
top = xx[:-1,1:]
bot = xx[1:,1:]
left = yy[1:,:-1]
right = yy[1:,1:]
np.column_stack(v.ravel()
for v in (top, left, top, right, bot, right, bot, left))
结果是单个矩阵,但列与所需的元组完全相同:
array([[ 0, 10, 0, 11, 1, 11, 1, 10],
[ 0, 11, 0, 12, 1, 12, 1, 11],
[ 0, 12, 0, 13, 1, 13, 1, 12],
[ 1, 10, 1, 11, 2, 11, 2, 10],
[ 1, 11, 1, 12, 2, 12, 2, 11],
[ 1, 12, 1, 13, 2, 13, 2, 12],
[ 2, 10, 2, 11, 3, 11, 3, 10],
[ 2, 11, 2, 12, 3, 12, 3, 11],
[ 2, 12, 2, 13, 3, 13, 3, 12]])
答案 1 :(得分:2)
在numpy之外(因为我根本不知道numpy ......)
import itertools
result = [list(itertools.product((x,x+1), (y,y+1))) for
x,y in itertools.product(range(0,3), range(10,13))]
导致
[[(0, 10), (0, 11), (1, 10), (1, 11)],
[(0, 11), (0, 12), (1, 11), (1, 12)],
[(0, 12), (0, 13), (1, 12), (1, 13)],
[(1, 10), (1, 11), (2, 10), (2, 11)],
[(1, 11), (1, 12), (2, 11), (2, 12)],
[(1, 12), (1, 13), (2, 12), (2, 13)],
[(2, 10), (2, 11), (3, 10), (3, 11)],
[(2, 11), (2, 12), (3, 11), (3, 12)],
[(2, 12), (2, 13), (3, 12), (3, 13)]]