Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

python - 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.

question from:https://stackoverflow.com/questions/65952742/all-the-combination-of-two-list-of-lists

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...