阅读量:2
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')]