Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python creating a list with itertools.product?

I'm creating a list with itertools from a list of ranges, so far I have this:

start_list = [xrange(0,201,1),xrange(0,201,2),xrange(0,201,5),xrange(0,201,10),xrange(0,201,20),xrange(0,201,50),xrange(0,201,100),xrange(0,201,200)]

Now, I know that if I were to try to run this next line it will kill my python interpreter:

next_list = list(itertools.product(*start_list))

What I'm wondering is would it be possible to put in an argument that checks each tuple, for a sum of its items and only puts them in next_list if equal to a certain amount?

Maybe something like:

next_list = list(itertools.product(*start_list,sum(tuples)=200))

I know this isn't right and I might need to start to re-think the way I'm going about this. Will start_list's ranges in the generator be too many to get through to build another list?

like image 699
tijko Avatar asked Jun 12 '12 01:06

tijko


People also ask

What does product () do in Python?

product() is used to find the cartesian product from the given iterator, output is lexicographic ordered. The itertools. product() can used in two different ways: itertools.

How do you create a cartesian product of two lists in Python?

Practical Data Science using Python As we know if two lists are like (a, b) and (c, d) then the Cartesian product will be {(a, c), (a, d), (b, c), (b, d)}. To do this we shall use itertools library and use the product() function present in this library. The returned value of this function is an iterator.

Is Itertools product faster than for loops?

That being said, the iterators from itertools are often significantly faster than regular iteration from a standard Python for loop.

Is Itertools product efficient?

Itertools will make your code stand out. Above all, it will make it more pythonic. One would question the need for itertools. They are faster and much more memory efficient.


1 Answers

Better to just use a list comprehension

new_list = [item for item in itertools.product(*start_list) if sum(item) == 200]
like image 195
John La Rooy Avatar answered Nov 01 '22 12:11

John La Rooy