pick combinations from multiple lists

后端 未结 2 1146
长情又很酷
长情又很酷 2020-12-17 10:26

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,         


        
相关标签:
2条回答
  • 2020-12-17 11:06

    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.
    
    0 讨论(0)
  • 2020-12-17 11:07

    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)
    
    0 讨论(0)
提交回复
热议问题