PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 9, 2022

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

 May 09, 2022     cartesian-product, itertools, product, python, tuples     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing