【问题标题】:How to get all coordinates for a n-dim array, given its dimensions给定维度,如何获取 n-dim 数组的所有坐标
【发布时间】:2020-03-12 07:03:52
【问题描述】:

假设你得到了一个 n-d 数组维度的元组,即 (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]]

【问题讨论】:

  • [[0,0,0],[0,1,0],[1,0,0],[1,1,0],[0,0,1],[ 0,1,1],[1,0,1],[1,1,1]] 不等于维度 = (2,2,2)...
  • 你能展示你目前的尝试吗?
  • @Zhubei-Federer:我不同意你的观点。 Python 索引从 0 开始。对于 2x2 数组,索引为:[0,0]、[0,1]、[1,0]、[1,1]。

标签: python list dimensions


【解决方案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]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-11
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 2021-08-19
    相关资源
    最近更新 更多