Computing the Cartesian Product of Lists
Obtaining the Cartesian product, or all possible combinations of values, from multiple lists poses a common challenge in programming. Consider the example of a list of lists:
somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ]
The Ideal Output:
The result we seek is a single list containing every possible combination of values from the input lists:
[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5), ...]
The Pythonic Solution: itertools.product
The Python standard library provides a powerful tool for this task: itertools.product. Available since Python 2.6, this function expects the input sequences as separate arguments.
import itertools for element in itertools.product(*somelists): print(element)
Alternatively, you can explicitly specify each sequence as an argument:
for element in itertools.product([1, 2, 3], ['a', 'b'], [4, 5]): print(element)
itertools.product will return a generator object that yields each combination as a tuple. To obtain the desired list, you can iterate over the generator and convert each tuple to a list if needed.
By utilizing itertools.product, you can efficiently compute the Cartesian product of multiple lists, avoiding the need for nested loops and ensuring a concise and readable solution to this common programming challenge.
The above is the detailed content of How Can I Efficiently Compute the Cartesian Product of Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!