Home >Backend Development >Python Tutorial >How can I efficiently generate all possible combinations from a list of lists in Python?

How can I efficiently generate all possible combinations from a list of lists in Python?

DDD
DDDOriginal
2024-12-10 11:58:14972browse

How can I efficiently generate all possible combinations from a list of lists in Python?

Combinations of a List of Lists in Python

In programming, combining elements from multiple lists is a common task. This question focuses on generating all possible combinations of items from a list of lists, regardless of its size.

To achieve this, the Python library offers an ingenious solution using the itertools.product function. This function takes a variable number of iterables as input and returns a Cartesian product, which essentially produces all possible combinations of elements from each iterable.

For example, let's consider the input list of lists: [[1,2,3],[4,5,6],[7,8,9,10]].

import itertools
a = [[1,2,3],[4,5,6],[7,8,9,10]]
combinations = list(itertools.product(*a))

The resulting combinations list will contain all possible combinations of the elements from the input lists:

[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 4, 10), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 5, 10),
(1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 6, 10), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 4, 10),
(2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 5, 10), (2, 6, 7), (2, 6, 8), (2, 6, 9), (2, 6, 10),
(3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 4, 10), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 5, 10),
(3, 6, 7), (3, 6, 8), (3, 6, 9), (3, 6, 10)]

Through the power of itertools.product, generating combinations from a list of lists becomes a concise and elegant operation in Python.

The above is the detailed content of How can I efficiently generate all possible combinations from a list of lists in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn