【发布时间】:2012-03-28 07:52:45
【问题描述】:
我有这个:
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 在每次迭代中都会推进最右边的元素。但现在我希望能够根据以下内容指定迭代顺序:
axes = (0, 1) # normal order
# output: (0, 0) (0, 1) (0, 2) (0, 3) (1, 0) (1, 1) (1, 2) (1, 3)
axes = (1, 0) # reversed order
# output: (0, 0) (1, 0) (2, 0) (3, 0) (0, 1) (1, 1) (2, 1) (3, 1)
如果shapes 具有三个维度,则axes 可能是例如(0, 1, 2) 或(2, 0, 1) 等,所以这不是简单地使用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))
关于如何正确执行此操作的任何想法?
【问题讨论】:
-
对于您的示例,
tpaxes是[1, 0],axes是(1, 0)。为了清楚起见,您可能希望更改示例数据,以便它们有所不同:) -
是的,axes=tpaxes 因为这是对二维矩阵的轴重新排序的唯一可能方法。对于 3d 矩阵,情况并非如此。例如,如果轴是
(2, 0, 1),那么 tpaxes 将是(1, 2, 0)。 -
我知道——只是想指出,在这种情况下,一个更复杂的例子会更好;没有冒犯。
-
唯一没有额外步骤的方法是编写自己的
product实现。我链接到一对你可以从前几天开始的this post aboutitertools.product。我的问题是为什么。如果您确实需要在某些特定情况下执行此操作,您只需将提供给产品的参数重新排序为正确的开始顺序,而无需更改生成的顺序。 -
你不能事后对
product的输出进行排序吗?