[英]How to get all coordinates for a n-dim array, given its dimensions
假设你得到一个 nd 数组维度的元组,即 (3,3) 是一个 3x3 矩阵,(4,5,6) 是一个 4x5x6 矩阵等。我如何编写一个可以返回一个函数所有可能的索引列表?
dimensions = (2,2)
get_coordinates(dimensions)
>>[[0,0],[0,1],[1,0],[1,1]]
或者
dimensions = (2,2,2)
get_coordinates(dimensions)
>>[[0,0,0],[0,1,0],[1,0,0],[1,1,0],[0,0,1],[0,1,1],[1,0,1],[1,1,1]]
您可以使用递归方法:
def gen(t):
if len(t) == 1:
yield from range(t[0])
else:
for e in range(t[0]):
for g in gen(t[1:]):
yield [e, *([g] if isinstance(g, int) else g)]
def get_coordinates(dim):
return list(gen(dim))
print(get_coordinates((2, 2)))
print(get_coordinates((2, 2, 2)))
输出:
[[0, 0], [0, 1], [1, 0], [1, 1]]
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.