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

发布于 2024-09-01 17:28:17 字数 306 浏览 2 评论 0原文

在 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] ]

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

In Python I have a list of n lists, each with a variable number of elements. How can I create a single list containing all the possible permutations:

For example

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

I want

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

Note I don't know n in advance. I thought itertools.product would be the right approach but it requires me to know the number of arguments in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

孤城病女 2024-09-08 17:28:17

您无需提前知道 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')]

You don't need to know n in advance to use 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')]
纵性 2024-09-08 17:28:17

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

>>> 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']]

You can do it with a multi-level list comprehension:

>>> 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']]
兰花执着 2024-09-08 17:28:17

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)]
>>>

itertools.product works for me.

>>> 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)]
>>>
嘿嘿嘿 2024-09-08 17:28:17

如果由于某种原因,您需要定义自己的方法而不使用 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]]

If, for some reason, you need to define your own method and not use itertools.product (e.g., for a interview question):

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]]) = }")

Output:

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]]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文