如何计算列表与自身的笛卡尔积

How to calculate a Cartesian product of a list with itself

例如,

list = [0, 1, 2]

我想要一个包含所有可能的 2 种组合的列表:

combinations = [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)]

在我看来,Python中itertools中的所有工具只能使(1,0)和(0,1)之一,而不是两者,我都需要。除了手动输入外,还有什么建议吗?

可以通过导入 itertools 来完成:

import itertools

list1 = [0, 1, 2]
print(list(itertools.product(list1,repeat=2)))

输出:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

资源: 你可以了解更多 - here

您正在寻找该列表与其自身的笛卡尔积,而不是排列或组合。因此你应该使用 itertools.productrepeat=2:

from itertools import product

li = [0, 1, 2]
print(list(product(li, repeat=2)))
>> [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]