Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make couple for elements from two list (different size) in Python?

I need to make couple for elements from two lists (two lists are different size)
Ex:

x = ([3,2], [4,6,-8])
y = ([-5,1,4], [13,9], [7,5,-1,10])

Result:

new_list = ([3, -5], [3, 1], [3, 4], [3, 13], [3, 9], [3, 7], [3, 5], [3, -1],[3, 10], [2, -5], [2, 1] ......<sorry, there're too many>.... [-8, 5], [-8, -1], [-8, 10])

Thanks for suppost!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In two steps, 1) flatten your list of lists, 2) itertools.product

Flatten your list of lists:
How to make a flat list out of a list of lists

flat_list = [item for sublist in t for item in sublist]

Use itertools to create the product of the two lists.

itertools.product(x, y)

Example from OP:

x = ([3,2], [4,6,-8])
y = ([-5,1,4], [13,9], [7,5,-1,10])
x_flat = [item for sublist in x for item in sublist]
y_flat = [item for sublist in y for item in sublist]
list(itertools.product(x_flat, y_flat))

result:

[(3, -5), (3, 1), (3, 4), (3, 13), (3, 9), (3, 7), (3, 5), (3, -1), (3, 10), (2, -5), (2, 1), (2, 4), (2, 13), (2, 9), (2, 7), (2, 5), (2, -1), (2, 10), (4, -5), (4, 1), (4, 4), (4, 13), (4, 9), (4, 7), (4, 5), (4, -1), (4, 10), (6, -5), (6, 1), (6, 4), (6, 13), (6, 9), (6, 7), (6, 5), (6, -1), (6, 10), (-8, -5), (-8, 1), (-8, 4), (-8, 13), (-8, 9), (-8, 7), (-8, 5), (-8, -1), (-8, 10)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading