【问题标题】:Calculating Cartesian product in Python在 Python 中计算笛卡尔积
【发布时间】:2021-11-19 15:47:42
【问题描述】:

有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)

b 的结果是

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

在我的项目中,('A','B') 的含义与('B','A') 是一样的,请问如何去掉b 的重复项?我想让 b 只保留('A','B'),('A','C'),('B','C')。谢谢!

【问题讨论】:

    标签: python list tuples cartesian-product


    【解决方案1】:

    您可以在单个数组上使用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')]
    

    【讨论】:

    • 我怎样才能把 ('A','A'), ('B','B'), ('C','C') 放到这个列表中?
    • 使用combinations
    • 很有用!
    猜你喜欢
    • 2011-03-24
    • 2017-03-07
    • 1970-01-01
    • 2013-04-20
    • 2021-02-17
    • 2019-04-20
    • 2011-01-26
    • 2012-02-24
    • 1970-01-01
    相关资源
    最近更新 更多