Linux 拨号vps windows公众号手机端

python笛卡尔积算法怎么实现

lewis 8年前 (2017-08-11) 阅读数 10 #程序编程
文章标签 python

Python中可以通过使用嵌套循环或使用itertools.product()函数来实现笛卡尔积算法。

方法一:使用嵌套循环

def cartesian_product(lists):
    result = [[]]
    for lst in lists:
        result = [x+[y] for x in result for y in lst]
    return result

lists = [[1, 2, 3], ['a', 'b', 'c'], ['x', 'y']]
result = cartesian_product(lists)
print(result)

输出结果:

[[1, 'a', 'x'], [1, 'a', 'y'], [1, 'b', 'x'], [1, 'b', 'y'], [1, 'c', 'x'], [1, 'c', 'y'], [2, 'a', 'x'], [2, 'a', 'y'], [2, 'b', 'x'], [2, 'b', 'y'], [2, 'c', 'x'], [2, 'c', 'y'], [3, 'a', 'x'], [3, 'a', 'y'], [3, 'b', 'x'], [3, 'b', 'y'], [3, 'c', 'x'], [3, 'c', 'y']]

方法二:使用itertools.product()函数

import itertools

lists = [[1, 2, 3], ['a', 'b', 'c'], ['x', 'y']]
result = list(itertools.product(*lists))
print(result)

输出结果与方法一相同:

[(1, 'a', 'x'), (1, 'a', 'y'), (1, 'b', 'x'), (1, 'b', 'y'), (1, 'c', 'x'), (1, 'c', 'y'), (2, 'a', 'x'), (2, 'a', 'y'), (2, 'b', 'x'), (2, 'b', 'y'), (2, 'c', 'x'), (2, 'c', 'y'), (3, 'a', 'x'), (3, 'a', 'y'), (3, 'b', 'x'), (3, 'b', 'y'), (3, 'c', 'x'), (3, 'c', 'y')]
版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门