- Python:获取 nd 数组的所有可能的数组属性。使用
itertools.product
?- 如果是,怎么做?
- 在 Python 中,我有两个 n 维 numpy 数组
A
和B
(B
是一个零数组)。 - 这样的方式
A.shape[i]<=B.shape[i]
,对于0
之间的任何 i和n
. 我想以这种方式创建一个 for 循环,每次迭代我都认为是A
到B
的不同子集, 这样每一个可能的位置都被占用直到 for 循环结束。
例如,A = np.array([[1,1,1],[1,1,1]])
和 B = np.zeros((3,4))
,我会得到这些(每次迭代其中一个):
1 1 1 0 0 1 1 1 0 0 0 0 0 0 0 0
1 1 1 0 0 1 1 1 1 1 1 0 0 1 1 1
0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 1
对于一个固定的n
维度是微不足道的,只需为每个维度使用嵌套的循环。
但是,我想要一个通用的 n
维度。
我的方法是使用 itertools.product
获取索引的所有组合。
在上面的示例中,product([0,1],[0,1])
, 将遍历 (0,0),(0,1),(1,0),(1,1)
,我会有我的索引。
但是,我不知道如何将参数值传递给通用 n
的乘积函数。 .
任何的想法?有更好的方法吗?
最佳答案
itertools 产品应该可以工作。
import numpy as np
from itertools import product
A = np.ones((2,3))
B = np.zeros((3,4))
r_rng = range(B.shape[0]-A.shape[0]+1)
c_rng = range(B.shape[1]-A.shape[1]+1)
for i,j in product(r_rng, c_rng):
C = B.copy()
C[i:i+A.shape[0],j:j+A.shape[1]]=A
print(C,'\n')
输出:
[[1. 1. 1. 0.]
[1. 1. 1. 0.]
[0. 0. 0. 0.]]
[[0. 1. 1. 1.]
[0. 1. 1. 1.]
[0. 0. 0. 0.]]
[[0. 0. 0. 0.]
[1. 1. 1. 0.]
[1. 1. 1. 0.]]
[[0. 0. 0. 0.]
[0. 1. 1. 1.]
[0. 1. 1. 1.]]
关于python - 如何获取numpy数组所有可能的数组属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62615758/