我有这个:
shape = (2, 4) # arbitrary, could be 3 dimensions such as (3, 5, 7), etc...
for i in itertools.product(*(range(x) for x in shape)):
print(i)
# output: (0, 0) (0, 1) (0, 2) (0, 3) (1, 0) (1, 1) (1, 2) (1, 3)
到目前为止,很好,itertools.product
在每次迭代中推进最右边的元素。但现在我希望能够根据以下内容指定迭代顺序:
如果shapes
有三个维度,axes
可能是(0, 1, 2)
或{reversed()
的问题。所以我写了一些代码,但是看起来效率很低:
axes = (1, 0)
# transposed axes
tpaxes = [0]*len(axes)
for i in range(len(axes)):
tpaxes[axes[i]] = i
for i in itertools.product(*(range(x) for x in shape)):
# reorder the output of itertools.product
x = (i[y] for y in tpaxes)
print(tuple(x))
有什么好办法吗?在
实际上,这是一本专门的手册。由于轴只重新排序一次,所以速度应该更快:
如果你有足够的内存空间:让
itertools.product
完成这项艰苦的工作,并使用zip
来切换轴。在小测试:
^{2}$如果没有太多的产品,以上版本是快速的。对于大的结果集,下面的方法更快,但是。。。使用
eval
(尽管以一种相当安全的方式):编辑:如果您不仅要更改迭代的顺序,还需要更改形状(如OP的示例中所示),则需要进行小的更改:
以及
eval
版本:测试:
我不知道这有多有效,但你应该能做这样的事。。。在
我尝试了4个维度,它似乎有效。;)
我只是交换一下尺寸然后再交换回来。在
相关问题 更多 >
编程相关推荐