python - 列表列表 : find combinations of elements

标签 python list cartesian-product

<分区>

假设我有一个包含 n 个列表的列表。有没有一种巧妙的方法来获得那些长度为 n 的列表的所有可能组合,每个元素保持它的位置。

这是一个例子:

lists=[[1],[2,3],[4,5]]

输出:

[[1,2,4],
 [1,3,4],
 [1,2,5],
 [1,3,5]]

最佳答案

您可以使用 itertools.product为此:

>>> import itertools
>>> lists = [[1], [2, 3], [4, 5]]
>>> list(itertools.product(*lists))
[(1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5)]

关于python - 列表列表 : find combinations of elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12805944/

相关文章:

python - 使用numpy构建两个数组的所有组合的数组

python - x 和 y 数组点的笛卡尔积转化为单个二维点数组

c++ - 当元素数 > 1000 时,如何制作 vector 的笛卡尔积?

python - pandas 列表列的频率计数

Python - 应用程序结构

python - Pandas:如果相邻列中的字符串包含来自另一个 DataFrame 的子字符串,则 DataFrame 列中的平均值

Python:根据值/条件创建子列表

Python 语法/列表切片问题 : What does this syntax mean?

c - 链表循环

python - 张量值不正确