Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternative (faster) war to 3 nested for loop python

Tags:

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
like image 273
Pierpaolo Avatar asked Dec 19 '13 14:12

Pierpaolo


1 Answers

You can try to take a look at itertools.product

Equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

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)

So in your case it can be:

import itertools

def vectorr(I,  J,  K):
    return itertools.product(range(K), range(J), range(I))
like image 95
Artsiom Rudzenka Avatar answered Oct 09 '22 09:10

Artsiom Rudzenka