Search code examples
pythoniterationproductpython-itertools

Itertools product of list


I have found this fonction, but i don't want

A = [[1,2],[3,4]]
print list(product(*A))
[(1, 3), (1, 4), (2, 3), (2, 4)]

I would like to have just that below in answer

[(1, 4),(2, 3)]

How can i do that please ?

In fact, i don't want to have a number at the same place in the original list in my final list.

I have made that :

def afficherListe(A):
n=len(A)
B=[]
for i in range (0,n,1):
    for j in range (0,n,1):
        if i!=j:
            B.append(A[i][j])
return B

But it doesn't work I have just [2,3] in answer...


Solution

  • I think that perhaps you want to get all tuples consisting of 1 item from each column and each row, as in a determinant calculation. If so:

    from itertools import permutations
    
    def afficherListe(A):
        """A is a square matrix. Returns all tuples used in det(A)"""
        n = len(A)
        return [tuple(A[i][j] for i,j in enumerate(p)) for p in permutations(range(n))]
    
    #tests:
    A = [[1,2],[3,4]]
    B = [[1,2,3],[4,5,6],[7,8,9]]
    print(afficherListe(A))
    print(afficherListe(B))
    

    Output:

    [(1, 4), (2, 3)]
    [(1, 5, 9), (1, 6, 8), (2, 4, 9), (2, 6, 7), (3, 4, 8), (3, 5, 7)]