Python itertools.product如何生成元组定义的n维数组
我希望使用itertools.product(或类似工具)从初始元组生成一组矩阵地址(作为元组) 例如Python itertools.product如何生成元组定义的n维数组,python,matrix,tuples,itertools,cartesian-product,Python,Matrix,Tuples,Itertools,Cartesian Product,我希望使用itertools.product(或类似工具)从初始元组生成一组矩阵地址(作为元组) 例如 (5,) # return the addresses for a 1-dimensional matrix of 5 columns, (4,3) # return the addresses for a 2-dimensional matrix of 4 columns and 3 rows. (5, 3, 2) # ditto for a 3D matrix 例如,将tupl
(5,) # return the addresses for a 1-dimensional matrix of 5 columns,
(4,3) # return the addresses for a 2-dimensional matrix of 4 columns and 3 rows.
(5, 3, 2) # ditto for a 3D matrix
例如,将tuple
init\u tuple
设置为(4,3)
这是怎么回事
product([1,2],[3,4]). # generates the cross product.
>(1, 3)
>(1, 4)
>(2, 3)
>(2, 4)
因此,我需要元组中每个I
的范围(0,I)
的叉积。
这意味着我想要这样的东西
product([0,1,2,3],[0,1,2])
获取元组中每个i的范围列表非常简单
[range(0, i) for i in init_tuple]
>[range(0, 3), range(0, 4)]
将列表作为参数提供只需一步之遥。(参数解包很酷)
[range(0, i) for i in init_tuple]
>[range(0, 3), range(0, 4)]
values = product(*[range(0, i) for i in init_tuple])
>(0, 0)
>(0, 1)
>(0, 2)
>(0, 3)
>(1, 0)
>(1, 1)
>(1, 2)
>(1, 3)
>(2, 0)
>(2, 1)
>(2, 2)
>(2, 3)