python - 删除 numpy 中的嵌套循环

标签 python numpy nested-loops

我一直在编写一个程序来强力检查数字序列以查找欧拉砖,但我想出的方法涉及三重循环。由于嵌套的 Python 循环非常慢,我想知道是否有更好的方法使用 numpy 来创建我需要的值数组。

#x=max side length of brick. User Input.    
for t in range(3,x):
    a=[];b=[];c=[];
    for u in range(2,t):
        for v in range(1,u):
                a.append(t)
                b.append(u)
                c.append(v)
    a=np.array(a)
    b=np.array(b)
    c=np.array(c)
    ...

是否有更好的方法使用 numpy 命令生成数组 af 值?

谢谢。

示例: 如果x=10,当t=3时我想得到:

a=[3]  
b=[2]     
c=[1]

第一次循环。之后,当 t=4 时:

a=[4, 4, 4]
b=[2, 3, 3]
c=[1, 1, 2]

第三次(t=5)我想要:

a=[5, 5, 5, 5, 5, 5]
b=[2, 3, 3, 4, 4, 4]
c=[1, 1, 2, 1, 2, 3]

依此类推,最大边长约为 5000 左右。

编辑:解决方案

a=array(3)
b=array(2)
c=array(1)
for i in range(4,x): #Removing the (3,2,1) check from code does not affect results.
    foo=arange(1,i-1)
    foo2=empty(len(foo))
    foo2.fill(i-1)
    c=hstack((c,foo))
    b=hstack((b,foo2))
    a=empty(len(b))
    a.fill(i)
    ...

现在工作速度快了很多倍。谢谢大家。

最佳答案

尝试使用 .empty 和 .fill (http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.fill.html)

关于python - 删除 numpy 中的嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6649839/

相关文章:

python - Pandas str.lower() 不适用于数据框列

python - 数组处理 - Python

python - 在 SciPy 中,csr_matrices 的奇特索引

python - 根据numpy python中的条件对二维数组进行子集化

c - 仅在第 6 个位置将循环值减 2

python - 如何在从源 Python 编译的上安装 Pip

python - 使用 Django-Celery 重试任务 - Django/Celery

python - OpenCV 图像减法 vs Numpy 减法

arrays - 嵌套 for 循环行为 - shell 脚本

r - 列出 R 中的所有组合