Python itertools模塊中的product函數
阿新 • • 發佈:2019-04-16
art abcd 可叠代對象 對象 utils nbsp too ble div
product
用於求多個可叠代對象的笛卡爾積(Cartesian Product),它跟嵌套的 for 循環等價.即:
product(A, B)
和 ((x,y) for x in A for y in B)一樣.
它的一般使用形式如下:
itertools.product(*iterables, repeat=1)
iterables是可叠代對象,repeat指定iterable重復幾次,即:
product(A,repeat=3)等價於product(A,A,A)
大概的實現邏輯如下(真正的內部實現不保存中間值):
def product(*args, repeat=1):# product(‘ABCD‘, ‘xy‘) --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 pools = [tuple(pool) for pool in args] * repeat result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result:yield tuple(prod)
Python itertools模塊中的product函數