溫馨提示×

python笛卡爾積算法怎么實現(xiàn)

小億
165
2023-12-01 11:09:04
欄目: 編程語言

Python中可以通過使用嵌套循環(huán)或使用itertools.product()函數(shù)來實現(xiàn)笛卡爾積算法。

方法一:使用嵌套循環(huán)

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()函數(shù)

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')]

0