permutations of two lists in python

后端 未结 5 1034
甜味超标
甜味超标 2020-12-02 12:57

I have two lists like:

list1 = [\'square\',\'circle\',\'triangle\']
list2 = [\'red\',\'green\']

How can I create all permutations of these

5条回答
  •  [愿得一人]
    2020-12-02 13:49

    I think what you are looking for is the product of two lists, not the permutations:

    #!/usr/bin/env python
    import itertools
    list1=['square','circle','triangle'] 
    list2=['red','green']
    for shape,color in itertools.product(list1,list2):
        print(shape+color)
    

    yields

    squarered
    squaregreen
    circlered
    circlegreen
    trianglered
    trianglegreen
    

    If you'd like both squarered and redsquare, then you could do something like this:

    for pair in itertools.product(list1,list2):
        for a,b in itertools.permutations(pair,2):
            print(a+b)
    

    or, to make it into a list:

    l=[a+b for pair in itertools.product(list1,list2)
       for a,b in itertools.permutations(pair,2)]
    print(l)
    

    yields

    ['squarered', 'redsquare', 'squaregreen', 'greensquare', 'circlered', 'redcircle', 'circlegreen', 'greencircle', 'trianglered', 'redtriangle', 'trianglegreen', 'greentriangle']
    

提交回复
热议问题