Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pick combinations from multiple lists

Tags:

I am new to python and I am struggling to form a combination of multiple lists. So, I have three (and possible more) looking like this:

uk_rock_stars=[1,2,3,4,5,6,7,8,9]
uk_pop_stars=[10,11,12,13,1,4,6,22,81]
us_stars=[22,34,44,7,33,99,22,77,99]
.
.

with all lists of the same length. Now, I would like to generate a combination list of them, with N being the total number of lists above. I am looking for a result looking like:

comb=[(1,10,22),(1,10,34),(1,10,44)...etc (all combinations)....]

such that, each combinations, say (1,10,22) is of same length as the number of original lists (in this case 3)

like image 600
AJW Avatar asked Mar 09 '13 00:03

AJW


People also ask

How do you generate all possible combinations of two lists in Python?

The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2.

How do you print all combinations of a list in Python?

combinations() module in Python to print all possible combinations. Given an array of size n, generate and print all possible combinations of r elements in array.


1 Answers

Read over this http://docs.python.org/2/library/itertools.html#itertools.product, it explains everything.

itertools is a package that has a bunch of useful functionality for iterating over collections. One useful feature is the product function which creates a generator that will iterate over the cartesian product of any number of iterable collections you give it.

The result of itertools.product is not a list, it is a generator. A python generator is similar to a coroutine in other languages. This means it will compute your combinations on an as needed basis. If you compute the product of three iterables that each have size 100, but you only use the first 10 or so, itertools.product will only compute 10 combinations instead of computing all 100^3 combinations.

If you actually want a list object instead of a generator (maybe you want to compute slices or something) call the list function and pass your generator object as an argument.

The following code produces all combinations and prints the results.

Code:

import itertools

uk_rock_stars=[1,2,3,4,5,6,7,8,9]
uk_pop_stars=[10,11,12,13,1,4,6,22,81]
us_stars=[22,34,44,7,33,99,22,77,99]

for combination in itertools.product(uk_rock_stars, uk_pop_stars, us_stars):
    print combination

Outputs:

(1, 10, 22)
(1, 10, 34)
(1, 10, 44)
(1, 10, 7)
(1, 10, 33)
(1, 10, 99)
(1, 10, 22)
(1, 10, 77)
(1, 10, 99)
(1, 11, 22)
(1, 11, 34)
(1, 11, 44)
(1, 11, 7)
(1, 11, 33)
(1, 11, 99)
(1, 11, 22)
(1, 11, 77)
(1, 11, 99)
...
etc.
like image 163
martega Avatar answered Oct 03 '22 20:10

martega