简体   繁体   中英

How to get all coordinates for a n-dim array, given its dimensions

Say you're given a tuple for the dimensions of an nd array, ie (3,3) is a 3x3 matrix, (4,5,6) is a 4x5x6 matrix, etc. How can I write a function that can return a list of all indices possible?

 dimensions = (2,2)
 get_coordinates(dimensions)
 >>[[0,0],[0,1],[1,0],[1,1]]

or

 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]]

you could use a recursive approach:

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)))

output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM