Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

python - 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...