Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 给定n维数组的维数,如何获取该数组的所有坐标_Python_List_Dimensions - Fatal编程技术网

Python 给定n维数组的维数,如何获取该数组的所有坐标

Python 给定n维数组的维数,如何获取该数组的所有坐标,python,list,dimensions,Python,List,Dimensions,假设你得到了一个n-d数组的尺寸元组,即(3,3)是3x3矩阵,(4,5,6)是4x5x6矩阵等等。 如何编写一个可以返回所有可能索引列表的函数 dimensions = (2,2) get_coordinates(dimensions) >>[[0,0],[0,1],[1,0],[1,1]] 或 您可以使用递归方法: def gen(t): if len(t) == 1: yield from range(t[0]) else:

假设你得到了一个n-d数组的尺寸元组,即(3,3)是3x3矩阵,(4,5,6)是4x5x6矩阵等等。 如何编写一个可以返回所有可能索引列表的函数

 dimensions = (2,2)
 get_coordinates(dimensions)
 >>[[0,0],[0,1],[1,0],[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]]

[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)。Python索引从0开始。对于2x2数组,索引为:[0,0]、[0,1]、[1,0]、[1,1]。
[[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]]