Monday, May 9, 2022

[FIXED] How do I use itertools.product() in python to loop over multiple arrays?

Issue

This is a part of my code:

m,n=list(map(int,input().split()))
for i in range(m):
    L=list(map(int,input().split()))
    if(i==0):
        K=L.copy()
        continue
    K=list(product(list(K),list(L)))

the input of the program would be:

4 """No.of arrays"""

2 5 3

3 7 4

1 5 3

3 5 1

I have used itertools.product to perform the cartesian product between the 4 arrays.

The output I get is of the form: [(((2, 3), 5),1).....(((3,4),3),5)]. How can I refine my code in a such that I get an output of the form: [(2,3,5,1).....(3,4,3,5)].


Solution

Something like this?

arrays = [[2, 5, 3], [3, 7, 4], [1, 2, 3], [3, 5, 1]]

list(product(*arrays))


Answered By - blueteeth
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.