简体   繁体   中英

All the combination of two list of lists

I have a Python question. I have two list of lists as follows:

    list_1 = [["A1","A2"],["B1","B2"],["C1","C2"]]
    list_2 = [["A3","A4"],["B3","B4"],["C3"]]

I am looking for all the possible combination of these two list with only one element from each list within list. Also if the combination has only one "C" it should come from list_1 (the list which has two "C"s). For instance:

    output:
    [["A1","A3"],["B1","B3"],["C1","C3"]]
    [["A2","A3"],["B1","B3"],["C2","C3"]]
    [["A1","A4"],["B2","B3"],["C2"]]

Can this be done with the basic Python library?

Edit

This is my best try so far:

    combi = []
    for i in range(len(list_1)):
        for j in range(len(list_1[i])):
            for k in range(len(list_2[i])):
                combi.extend([list_1[i][j],list_2[i][k]])

However, this did not get me what I hoped for.

Not sure I really understand your req. some of the output is inconsistent or missing as my post indicated. So I've tried to guess what you want to make the combinations from each list (one at a time) as your title description stated.

You can modify the sample to suite your needs, if there is a gap in understanding. (this should be very close... though)

from itertools import product

list_1 = [["A1","A2"],["B1","B2"]] #,["C1","C2"]]   # for simple test, reduce C-lst
list_2 = [["A3","A4"],["B3","B4"]] #,["C3"]]
combs =  []   # set()

for one in list_1:
    for two in list_2:
      
        for p in product(one, two):
            #print(p)      # can comment out
            combs.append(list(p))
               

print(combs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM