J
J
Jekson2021-08-28 17:31:35
Python
Jekson, 2021-08-28 17:31:35

Get combination of two tuples?

I'm looking for a one-liner to get combinations of elements of two tuples.

tuple_one = ('one',  'two', .... 'thousand')    # name
tuple_two = ('blue',  'black',  'yellow', .......)    # color

We need to get a list of tuples, each element from the first tuple corresponds to all the elements of the second tuple. That is, if you visually describe, there is a product and there are colors of the product, you need pairs containing all color options for the product.
[('one',  'blue'),  ('one',  'black',)  ('one',  'yelow') ....... ('two',  'blue'),  ('two',  'black',)  ('two',  'yelow')]

As a result, if there are 1000 products and 5 colors at the output, we have a list with a length of 5k elements

. Once I saw a solution using a built-in module optimized for such tasks (such as collection or itertools), but now I could not find it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sswwssww, 2021-08-28
@Lepilov

from itertools import product


tuple_one = ('one',  'two', 'thousand')    # name
tuple_two = ('blue', 'black',  'yellow')    # color
print(list(product(tuple_one, tuple_two)))

conclusion:
[('one', 'blue'), ('one', 'black'), ('one', 'yellow'), ('two', 'blue'), ('two', 'black'), ('two', 'yellow'), ('thousand', 'blue'), ('thousand', 'black'), ('thousand', 'yellow')]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question