Is there an algorithm to find unique combinations of 2 lists? 5 lists?

后端 未结 7 2402
醉话见心
醉话见心 2020-12-20 06:29

I have N Lists I\'d like to find unique combinations of. I\'ve written it out on my whiteboard and it all seems to have a pattern, I just haven\'t found it

相关标签:
7条回答
  • 2020-12-20 06:58

    I'm assuming that you want the Cartesian product - all possible lists created by choosing exactly one element from each list. You can implement it recursively, like this:

    def cartesian_product(l):
        if l:
            for b in cartesian_product(l[1:]):
                for a in l[0]:
                    yield [a] + b
        else:
            yield []        
    
    l = [
     [ 'a', 'b' ],
     [ 'c', 'd', 'e' ],
     [ 'f', 'g' ],
    ]
    
    for x in cartesian_product(l):
        print x
    

    Update: ~unutbu's suggestion of itertools.product is better, but I'll leave this here anyway.

    0 讨论(0)
提交回复
热议问题