Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the cartesian product of a series of lists?

How can I get the Cartesian product (every possible combination of values) from a group of lists?

Input:

somelists = [    [1, 2, 3],    ['a', 'b'],    [4, 5] ] 

Desired output:

[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...] 
like image 510
ʞɔıu Avatar asked Feb 10 '09 19:02

ʞɔıu


People also ask

How do you find the Cartesian product for a list set?

The Cartesian square of a set X is the Cartesian product X2 = X × X. An example is the 2-dimensional plane R2 = R × R where R is the set of real numbers: R2 is the set of all points (x,y) where x and y are real numbers (see the Cartesian coordinate system).

What is Cartesian product in Python?

The cartesian product of two sets will be a set of all possible ordered pairs with the first element of each ordered pair from the first set and the second element from the second set. We can find the cartesian product of sets saved as a 2D list using the following methods in Python.

How do you create a Cartesian product?

In mathematics, the Cartesian Product of sets A and B is defined as the set of all ordered pairs (x, y) such that x belongs to A and y belongs to B. For example, if A = {1, 2} and B = {3, 4, 5}, then the Cartesian Product of A and B is {(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)}.


1 Answers

itertools.product

Available from Python 2.6.

import itertools  somelists = [    [1, 2, 3],    ['a', 'b'],    [4, 5] ] for element in itertools.product(*somelists):     print(element) 

Which is the same as,

for element in itertools.product([1, 2, 3], ['a', 'b'], [4, 5]):     print(element) 
like image 91
Kenan Banks Avatar answered Oct 03 '22 04:10

Kenan Banks