在Python中计算笛卡尔积



有两个相同的数组,A=np.array(['A','B','C']),B=np.array(['A','B','C']),我计算了A和B的笛卡尔积:

import numpy as np
from itertools import product
b=product(A,B)
b的结果是
[('A','A'),('A','B'),('A','C'),('B','A'),('B','B'),('B','C'),('C','A'),('C','B'),('C','C)]

在我的project中,('A','B')的意思和('B','A')是一样的,我怎么能去掉B的重复呢?我想让b只储备(A, b), (' A ', ' C '),("b"、"C")。谢谢!

您可以在单个数组上使用combinations_with_replacement:

from itertools import combinations_with_replacement
list(combinations_with_replacement(A, r=2))

输出:

[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]

排除自组合:

from itertools import combinations
list(combinations(A, r=2))

输出:

[('A', 'B'), ('A', 'C'), ('B', 'C')]

最新更新