permutations of two lists in python

后端 未结 5 1036
甜味超标
甜味超标 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:53

    You want the itertools.product method, which will give you the Cartesian product of both lists.

    >>> import itertools
    >>> a = ['foo', 'bar', 'baz']
    >>> b = ['x', 'y', 'z', 'w']
    
    >>> for r in itertools.product(a, b): print r[0] + r[1]
    foox
    fooy
    fooz
    foow
    barx
    bary
    barz
    barw
    bazx
    bazy
    bazz
    bazw
    

    Your example asks for the bidirectional product (that is, you want 'xfoo' as well as 'foox'). To get that, just do another product and chain the results:

    >>> for r in itertools.chain(itertools.product(a, b), itertools.product(b, a)):
    ...   print r[0] + r[1]
    

提交回复
热议问题