Nested for loops in Python versus map function

I am working on python and currently have the following code:

list = [] for a in range(100): for b in range(100): for c in range(100): list.append(run(a,b,c)) 

where run (a, b, c) returns an integer (for example, it can multiply three numbers together). Is there a faster way to either iterate over these numbers or use the map function?

Thanks:)

+4
source share
5 answers

Take a look at the itertools-module and, in particular, the product method

usage example:

 for i in itertools.product(range(0,100), repeat=3): #do stuff with i list.append(run(i[0],i[1],i[2])) 

Note that a function call can be shortened to:

 list.append(run(*i)) 

in the above example. see docs.python.org for an explanation of unpacking argument lists.

As an example, the output from product(range(0,2), repeat=3)) as follows:

 (0, 0, 0) (0, 0, 1) (0, 1, 0) (0, 1, 1) (1, 0, 0) (1, 0, 1) (1, 1, 0) (1, 1, 1) 
+8
source

I think you can use imap for this:

 from itertools import imap result = list(imap(run, range(100), range(100), range(100))) 

imap gives the result ... so if you want to iterate over the results, don't use list ()

+2
source
 from itertools import product my_list = [run(a, b, c) for a, b, c in product(xrange(100), xrange(100), xrange(100))] 

Or:

 from itertools import product my_list = [run(a, b, c) for a, b, c in product(xrange(100), repeat=3)] 
+1
source
 import itertools li = [run(*triple) for triple in itertools.product(xrange(100), repeat=3)] 
0
source

an alternative, depending on what you want to do exactly:

 my_array = numpy.tile(numpy.arange(100),(3,1)).T def run(row): return numpy.prod(row, 0) [run(row) for row in my_array] 

Of course, it all depends on run , for example. if you want to take the product, you can also work with the whole array, which is much faster:

 my_product = run(my_array.T) my_product = numpy.prod(my_array, 1) 
0
source

All Articles