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

Time:12-21

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!

CodePudding user response:

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)]

CodePudding user response:

Your x, y and new_list in the examples are actually tuples and not lists, because you use () instead of [].

Based on your expected result, I assume that you don't really need lists of lists here, you just take flat lists:

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

And find each combination between x and y. Which can be done using itertools.product

CodePudding user response:

Using itertools chain and product:

from itertools import product, chain

new_list = list(product(chain(*x), chain(*y)))
[(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)]

CodePudding user response:

The simplest way is to use itertools.product after you flattened your lists:

x = ([3,2], [4,6,-8])
y = ([-5,1,4], [13,9], [7,5,-1,10])
x_flatten = [item for sublist in x for item in sublist]
y_flatten = [item for sublist in y for item in sublist]

result = list(itertools.product(x_flatten, y_flatten))
  • Related