简体   繁体   English

替代(更快)的战争到3嵌套的循环python

[英]alternative (faster) war to 3 nested for loop python

How can i made this function faster? 我怎样才能更快地完成这个功能? (I call it a lot of time and it could result in some speed improving) (我称之为很多时间,可能会提高速度)

def vectorr(I,  J,  K):
    vect = []
    for k in range(0,  K):
        for j in range(0, J):
            for i in range(0, I):
                vect.append([i, j, k])
    return vect

You can try to take a look at itertools.product 您可以尝试查看itertools.product

Equivalent to nested for-loops in a generator expression. 等效于生成器表达式中的嵌套for循环。 For example, product(A, B) returns the same as ((x,y) for x in A for y in B). 例如,乘积(A,B)与A中的x的((x,y)相同,对于B中的y,返回相同的值)。

The nested loops cycle like an odometer with the rightmost element advancing on every iteration. 嵌套循环像里程表一样循环,最右边的元素在每次迭代时前进。 This pattern creates a lexicographic ordering so that if the input's iterables are sorted, the product tuples are emitted in sorted order. 此模式创建了一个词典排序,以便在输入的可迭代内容进行排序时,产品元组按排序顺序发出。

Also no need in 0 while calling range(0, I) and etc - use just range(I) 调用范围(0,I)等时也不需要0 - 只使用范围(I)

So in your case it can be: 所以在你的情况下它可以是:

import itertools

def vectorr(I,  J,  K):
    return itertools.product(range(K), range(J), range(I))

You said you want it to be faster. 你说你希望它更快。 Let's use NumPy! 让我们用NumPy吧!

import numpy as np

def vectorr(I, J, K):
    arr = np.empty((I*J*K, 3), int)
    arr[:,0] = np.tile(np.arange(I), J*K)
    arr[:,1] = np.tile(np.repeat(np.arange(J), I), K)
    arr[:,2] = np.repeat(np.arange(K), I*J)
    return arr

There may be even more elegant tweaks possible here, but that's a basic tiling that gives the same result (but as a 2D array rather than a list of lists). 这里可能有更优雅的调整,但这是一个基本的平铺,给出相同的结果(但作为2D数组而不是列表列表)。 The code for this is all implemented in C, so it's very, very fast--this may be important if the input values may get somewhat large. 这个代码全部用C语言实现,所以非常非常快 - 如果输入值有些大,这可能很重要。

The other answers are more thorough and, in this specific case at least, better, but in general, if you're using Python 2, and for large values of I, J, or K, use xrange() instead of range() . 其他答案更彻底,在这个特定情况下至少更好,但一般来说,如果你使用Python 2,并且对于I,J或K的大值,使用xrange()而不是range() xrange gives a generator-like object, instead of constructing a list, so you don't have to allocate memory for the entire list. xrange提供类似于生成器的对象,而不是构造列表,因此您不必为整个列表分配内存。

In Python 3, range works like Python 2's xrange . 在Python 3中, range就像Python 2的xrange

import numpy

def vectorr(I,J,K):
   val = numpy.indices( (I,J,K))
   val.shape = (3,-1)
   return val.transpose() # or val.transpose().tolist()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM