1. 程式人生 > >python中笛卡爾積原始碼及實際使用

python中笛卡爾積原始碼及實際使用

問題:對於多個集合或列表,每次只從這多個集合或列表中取出一個元素,求所有的組合方式?

如何自己寫可能就想到多重for迴圈,但是,當使用多重for迴圈時,如果集合或列表數過多,則非常繁瑣!

python標準庫提供了笛卡爾積這一方法:itertools.product()

原始碼:(改動了一點點,只針對這一問題)

def product(*args):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    pools = map(tuple, args)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)
  
if __name__ == '__main__':
    a= [1,2,3]
    b = [5,6,7]
    for i in product(a,b):
        print(i)

結果:

(1, 5)
(1, 6)
(1, 7)
(2, 5)
(2, 6)
(2, 7)
(3, 5)
(3, 6)
(3, 7)

實際使用時,可能存在任意個列表或集合,此時可以對任意個列表包裝起來,實際操作:

if __name__ == '__main__':
    a= [1,2,3]
    b = [5,6,7]
    c = [a,b]
    for i in product(*c):
        print(i)

如上所示,即將多個列表放在一個列表內,然後在這個大列表前面加一個*.