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?
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.
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.
That being said, the iterators from itertools are often significantly faster than regular iteration from a standard Python for loop.
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.
Better to just use a list comprehension
new_list = [item for item in itertools.product(*start_list) if sum(item) == 200]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With