[英]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.