How to apply itertools.product to elements of a list of lists?

前端 未结 3 1991
迷失自我
迷失自我 2020-11-30 01:29

I have a list of arrays and I would like to get the cartesian product of the elements in the arrays.

I will use an example to make this more concrete...

iter

相关标签:
3条回答
  • 2020-11-30 02:08
    >>> arrays = [(-1,+1), (-2,+2), (-3,+3)]
    >>> list(itertools.product(*arrays))
    [(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3), (1, -2, -3), (1, -2, 3), (1, 2, -3), (1, 2, 3)]
    
    0 讨论(0)
  • 2020-11-30 02:15
    >>> list(itertools.product(*arrays))
    [(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3), (1, -2, -3), (1, -2, 3), (1, 2, -3), (1, 2, 3)]
    

    This will feed all the pairs as separate arguments to product, which will then give you the cartesian product of them.

    The reason your version isn't working is that you are giving product only one argument. Asking for a cartesian product of one list is a trivial case, and returns a list containing only one element (the list given as argument).

    0 讨论(0)
  • 2020-11-30 02:17

    you can do it in three rurch using itertools.product

    lst=[]
    arrays = [(-1,+1), (-2,+2), (-3,+3)]  
    
    import itertools 
    
    for i in itertools.product(*arrays):
             lst.append(i)
    
    
    
    print(lst)
    

    0 讨论(0)
提交回复
热议问题