python - 任意数量嵌套 for 循环的算法

标签 python algorithm numpy

我正在尝试找出一种算法来将我的代码推广为参数的任意整数值,该参数在我的代码中控制嵌套 for 循环的数量。我的代码示意性地看起来像

A = numpy matrix of dimension (n x m)

For i = 0:p
 For j = 0:q
  ...
   For l = 0:z

     X[counter] = A[0]*i + A[1]*j + ... + A[n]*l
     counter = counter + 1

X = numpy matrix of dimension (p*q*...*z x len(A[0]))

其中for循环的数量由任意整数控制。

感谢您的建议!

最佳答案

正如所指出的,这会很快爆发。但是您可以使用笛卡尔积迭代器:

import itertools
import numpy as np

# Create a list with ranges:
rngs=np.array([p,q,..,z])

#Initialize X empty
X = np.empty((rngs.prod(), A.shape[0]))

#Cycle over all cartesian products
for i,t in enumerate(itertools.product(*[range(i) for i in rngs])):
    X[i,:] = sum([A[i,:] * t[i] for i in range(len(t))])

测试数据:

A = np.random.randint(10, size=(10, 10))
A
array([[8, 5, 0, 2, 0, 4, 5, 5, 0, 9],
       [7, 0, 5, 9, 9, 4, 8, 2, 6, 8],
       [4, 3, 8, 5, 2, 5, 4, 8, 6, 1],
       [0, 5, 6, 5, 5, 0, 8, 5, 4, 9],
       [3, 3, 2, 6, 6, 9, 7, 7, 3, 3],
       [4, 0, 7, 2, 3, 2, 2, 4, 1, 2],
       [6, 2, 5, 9, 9, 9, 4, 7, 7, 3],
       [6, 3, 4, 9, 0, 3, 8, 1, 6, 8],
       [6, 5, 6, 0, 8, 7, 9, 0, 7, 4],
       [2, 1, 4, 1, 3, 8, 3, 3, 2, 9]])

rngs = np.random.randint(1, 5, size=10)
rngs
array([4, 2, 1, 2, 2, 3, 4, 4, 2, 4])

X = np.empty((rngs.prod(), A.shape[0]))

for i,t in enumerate(itertools.product(*[range(i) for i in rngs])):
    X[i,:] = sum([A[i,:] * t[i] for i in range(len(t))])

X
array([[  0.,   0.,   0., ...,   0.,   0.,   0.],
       [  2.,   1.,   4., ...,   3.,   2.,   9.],
       [  4.,   2.,   8., ...,   6.,   4.,  18.],
       ...,
       [ 86.,  44.,  64., ...,  64.,  63.,  97.],
       [ 88.,  45.,  68., ...,  67.,  65., 106.],
       [ 90.,  46.,  72., ...,  70.,  67., 115.]])

关于python - 任意数量嵌套 for 循环的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59052383/

相关文章:

c++ - 将算法 C++ 无效操作数替换为二进制表达式

algorithm - 您能说出这种音频压缩算法吗?

Python - 使用 Ipyvolume 库在 x、y 和 z 轴上绘制不同颜色的问题

应用自定义函数后获取字典最大值的Pythonic方法

python - 使 View 只能通过重定向访问,并且只能从 Django 中的一个 View 访问

python - 多个单词选项

python - 扩展 mnist 数据库

Python Graphene 处理多对多关系

java - 在java中生成半百万个唯一整数

python - 在 cython 中修剪一个 numpy 数组