Python 中一组列表的所有可能排列

问题描述 投票:0回答:4

在 Python 中,我有一个包含 n 个列表的列表,每个列表都有可变数量的元素。如何创建包含所有可能排列的单个列表:

例如

[ [ a, b, c], [d], [e, f] ]

我要

[ [a, d, e] , [a, d, f], [b, d, e], [b, d, f], [c, d, e], [c, d, f] ]

注意我事先不知道。我认为 itertools.product 是正确的方法,但它要求我提前知道参数的数量

python list permutation
4个回答
119
投票

你不需要提前知道

n
使用
itertools.product

>>> import itertools
>>> s=[ [ 'a', 'b', 'c'], ['d'], ['e', 'f'] ]
>>> list(itertools.product(*s))
[('a', 'd', 'e'), ('a', 'd', 'f'), ('b', 'd', 'e'), ('b', 'd', 'f'), ('c', 'd', 'e'), ('c', 'd', 'f')]

7
投票

您可以通过多级列表理解来做到这一点:

>>> L1=['a','b','c']
>>> L2=['d']
>>> L3=['e','f']
>>> [[i,j,k] for i in L1 for j in L2 for k in L3]
[['a', 'd', 'e'], ['a', 'd', 'f'], ['b', 'd', 'e'], ['b', 'd', 'f'], ['c', 'd', 'e'], ['c', 'd', 'f']]

6
投票

itertools.product 对我有用。

>>> l=[ [ 1, 2, 3], [4], [5, 6] ]
>>> list(itertools.product(*l))
[(1, 4, 5), (1, 4, 6), (2, 4, 5), (2, 4, 6), (3, 4, 5), (3, 4, 6)]
>>> l=[ [ 1, 2, 3], [4], [5, 6],[7,8] ]
>>> list(itertools.product(*l))
[(1, 4, 5, 7), (1, 4, 5, 8), (1, 4, 6, 7), (1, 4, 6, 8), (2, 4, 5, 7), (2, 4, 5, 8), (2, 4, 6, 7), (2, 4, 6, 8), (3, 4, 5, 7), (3, 4, 5, 8), (3, 4, 6,
 7), (3, 4, 6, 8)]
>>>

0
投票

如果出于某种原因,您需要定义自己的方法而不使用

itertools.product
(例如,对于面试问题):

from typing import Any, Optional

def cartesian_product(values: list[list[Any]],
                      partial_result: Optional[list[Any]] = None,
                      result: Optional[list[list[Any]]] = None) -> list[list[Any]]:
    """
    Computes the cartesian product of a list of lists. This function is a 
    recursive implementation and gives the same output as the function 
    itertools.product() from the Python standard library.

    :param values: A list of lists for which the cartesian product is computed.
    :param partial_result: A list that accumulates the current combination of values. 
                           This parameter is mainly used during the recursion.
    :param result: A list of all combinations that have been considered so far. 
                   This parameter is mainly used during the recursion.
    :return: A list of lists, where each inner list is one combination of 
             elements from the input lists.
    """
    if partial_result is None:
        partial_result = []
    if result is None:
        result = []
    if values:
        for v in values[0]:
            cartesian_product(values[1:], partial_result + [v], result)
    else:
        result.append(partial_result)
    return result

print(f"{cartesian_product([['a', 'b', 'c'], ['d'], ['e', 'f']]) = }")
print(f"{cartesian_product([[1, 2, 3], [4], [5, 6]]) = }")

输出:

cartesian_product([['a', 'b', 'c'], ['d'], ['e', 'f']]) = [['a', 'd', 'e'], ['a', 'd', 'f'], ['b', 'd', 'e'], ['b', 'd', 'f'], ['c', 'd', 'e'], ['c', 'd', 'f']]
cartesian_product([[1, 2, 3], [4], [5, 6]]) = [[1, 4, 5], [1, 4, 6], [2, 4, 5], [2, 4, 6], [3, 4, 5], [3, 4, 6]]
© www.soinside.com 2019 - 2024. All rights reserved.