All combinations of a list of lists

后端 未结 7 1578
离开以前
离开以前 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:55

    One can use base python for this. The code needs a function to flatten lists of lists:

    def flatten(B):    # function needed for code below;
        A = []
        for i in B:
            if type(i) == list: A.extend(i)
            else: A.append(i)
        return A
    

    Then one can run:

    L = [[1,2,3],[4,5,6],[7,8,9,10]]
    
    outlist =[]; templist =[[]]
    for sublist in L:
        outlist = templist; templist = [[]]
        for sitem in sublist:
            for oitem in outlist:
                newitem = [oitem]
                if newitem == [[]]: newitem = [sitem]
                else: newitem = [newitem[0], sitem]
                templist.append(flatten(newitem))
    
    outlist = list(filter(lambda x: len(x)==len(L), templist))  # remove some partial lists that also creep in;
    print(outlist)
    

    Output:

    [[1, 4, 7], [2, 4, 7], [3, 4, 7], 
    [1, 5, 7], [2, 5, 7], [3, 5, 7], 
    [1, 6, 7], [2, 6, 7], [3, 6, 7], 
    [1, 4, 8], [2, 4, 8], [3, 4, 8], 
    [1, 5, 8], [2, 5, 8], [3, 5, 8], 
    [1, 6, 8], [2, 6, 8], [3, 6, 8], 
    [1, 4, 9], [2, 4, 9], [3, 4, 9], 
    [1, 5, 9], [2, 5, 9], [3, 5, 9], 
    [1, 6, 9], [2, 6, 9], [3, 6, 9], 
    [1, 4, 10], [2, 4, 10], [3, 4, 10], 
    [1, 5, 10], [2, 5, 10], [3, 5, 10], 
    [1, 6, 10], [2, 6, 10], [3, 6, 10]]
    

提交回复
热议问题