AJW
AJW

Reputation: 5863

pick combinations from multiple lists

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)

Upvotes: 23

Views: 17964

Answers (2)

martega
martega

Reputation: 2143

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.

Upvotes: 34

grc
grc

Reputation: 23555

I think this is what you're looking for:

import itertools
comb = itertools.product(uk_rock_stars, uk_pop_stars, us_stars)

It will give you an iterator object, which may or may not be what you want. To convert it to a normal list, just use this:

comb = list(comb)

Upvotes: 5

Related Questions