【问题标题】:Given a list of lists, how do I create a matrix of all possible combinations of values in Python? [duplicate]给定一个列表列表,如何在 Python 中创建一个包含所有可能值组合的矩阵? [复制]
【发布时间】:2021-07-21 16:50:51
【问题描述】:

我知道如何创建组合矩阵,但我想要更动态的东西。例如,下面创建了一个包含 A、B 和 C 的所有可能组合的矩阵:

A = [0, 1, 2]
B = [3, 5, 7]
C = [10, 20, 30]

MATRIX = []

for a in A:
   for b in B:
      for c in C:
         MATRIX.append([a, b, c])

我想要更动态的东西,我可以有 A、B、C、.....N 列表。我只需要定义每个列表中的值,然后我希望它生成一个包含所有可能组合的矩阵。

我该怎么做?

【问题讨论】:

标签: python combinations permutation


【解决方案1】:

使用itertools.product,您可以传递任意数量的可迭代对象:

from itertools import product
print(list(product(A, B, C)))

输出:

[(0, 3, 10), (0, 3, 20), (0, 3, 30), (0, 5, 10), (0, 5, 20), (0, 5, 30), (0, 7, 10), (0, 7, 20), (0, 7, 30), (1, 3, 10), (1, 3, 20), (1, 3, 30), (1, 5, 10), (1, 5, 20), (1, 5, 30), (1, 7, 10), (1, 7, 20), (1, 7, 30), (2, 3, 10), (2, 3, 20), (2, 3, 30), (2, 5, 10), (2, 5, 20), (2, 5, 30), (2, 7, 10), (2, 7, 20), (2, 7, 30)]

如果你想要一个列表列表,而不是元组列表,只需编写一个简单的“列表推导”即可。

【讨论】:

    猜你喜欢
    • 2020-02-28
    • 2018-08-01
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多