[英]Calculating Cartesian product in Python
There are 2 same arrays, A=np.array(['A','B','C']),B=np.array(['A','B','C']), I calculated the Cartesian product of A and B:有2个相同的数组,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)
the result of b is b 的结果是
[('A','A'),('A','B'),('A','C'),('B','A'),('B','B'),('B','C'),('C','A'),('C','B'),('C','C)]
In my project, the meaning of ('A','B') is the same as ('B','A'), How could I drop the duplications of b?在我的项目中,('A','B') 的含义与('B','A') 的含义相同,我怎样才能删除b 的重复项? I want to make b only reserve ('A','B'), ('A','C'), ('B','C').
我想让 b 只保留('A','B'),('A','C'),('B','C')。 Thanks!
谢谢!
You can use combinations_with_replacement
on a single array:您可以在单个数组上使用
combinations_with_replacement
:
from itertools import combinations_with_replacement
list(combinations_with_replacement(A, r=2))
output:输出:
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]
from itertools import combinations
list(combinations(A, r=2))
output:输出:
[('A', 'B'), ('A', 'C'), ('B', 'C')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.