美文网首页
笛卡尔积

笛卡尔积

作者: 小宝瓜 | 来源:发表于2020-02-25 17:51 被阅读0次

    首先知道啥是笛卡尔积,百度百科中解释是这样的:

    笛卡尔乘积是指在数学中,两个集合X和Y的笛卡尔积(Cartesian product),又称直积,表示为X × Y,第一个对象是X的成员而第二个对象是Y的所有可能有序对的其中一个成员。

    通俗理解就是一个集合中的所有元素与另外一个集合中的所有元素的所有组合。需要注意有先后顺序。

    举个例子:
    集合A={a,b}, B={0,1,2},则
    A×B={(a, 0), (a, 1), (a, 2), (b, 0), (b, 1), (b, 2)}
    B×A={(0, a), (0, b), (1, a), (1, b), (2, a), (2, b)}

    再如:
    集合A是所有声母,集合B是所有韵母。那么集合A与集合B的笛卡尔积就是所有的拼音组合。

    python默认迭代器库itertools提供笛卡尔积计算函数product

    用法:

    itertools.product(*iterables, repeat=1)
    

    示例1:
    计算姓氏“张、李”和名“一、二、三”所有搭配组合。

    # -*- coding:utf-8 -*-
    from itertools import product
    
    x = ["张", "李"]
    m = ["一", "二", "三"]
    
    for p in product(x, m):
        print(p)
    
    ------------output----------------------
    ('张', '一')
    ('张', '二')
    ('张', '三')
    ('李', '一')
    ('李', '二')
    ('李', '三')
    

    示例2:
    当然不仅仅是两个集合,多个集合也同样可以。
    比如字典的生成。

    # -*- coding:utf-8 -*-
    from itertools import product
    
    for pw in product(["pass", "Pass"], ["word", "Word"], ["123", "456"]):
        print(pw)
    ------------output----------------------
    ('pass', 'word', '123')
    ('pass', 'word', '456')
    ('pass', 'Word', '123')
    ('pass', 'Word', '456')
    ('Pass', 'word', '123')
    ('Pass', 'word', '456')
    ('Pass', 'Word', '123')
    ('Pass', 'Word', '456')
    

    当然如果字典生成不需要有序的话,可以使用另外两个函数permutations
    combinations

    In [19]: list(permutations(["zhang", 3, '@'], 3))
    Out[19]:
    [('zhang', 3, '@'),
     ('zhang', '@', 3),
     (3, 'zhang', '@'),
     (3, '@', 'zhang'),
     ('@', 'zhang', 3),
     ('@', 3, 'zhang')]
    
    In [20]: list(combinations(["zhang", 3, '@'], 3))
    Out[20]: [('zhang', 3, '@')]
    

    两者的区别在于,如果几个集合的元素相同,但位置顺序不同,permutations记为不同集,而combinations记为同一集合,也就是permutations为有序集合combinations为无序集合。

    相关文章

      网友评论

          本文标题:笛卡尔积

          本文链接:https://www.haomeiwen.com/subject/ragrxhtx.html