All combinations of a list of lists

后端 未结 7 1468
离开以前
离开以前 2020-11-22 00:38

I\'m basically looking for a python version of Combination of List>

Given a list of lists, I need a new list that gives all the possible combin

7条回答
  •  长情又很酷
    2020-11-22 00:59

    Nothing wrong with straight up recursion for this task, and if you need a version that works with strings, this might fit your needs:

    combinations = []
    
    def combine(terms, accum):
        last = (len(terms) == 1)
        n = len(terms[0])
        for i in range(n):
            item = accum + terms[0][i]
            if last:
                combinations.append(item)
            else:
                combine(terms[1:], item)
    
    
    >>> a = [['ab','cd','ef'],['12','34','56']]
    >>> combine(a, '')
    >>> print(combinations)
    ['ab12', 'ab34', 'ab56', 'cd12', 'cd34', 'cd56', 'ef12', 'ef34', 'ef56']
    

提交回复
热议问题