gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:34:24 25 4
gpt4 key购买 nike

我正在尝试找出一种算法来将我的代码推广为参数的任意整数值,该参数在我的代码中控制嵌套 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com