隨着品牌新的Python 2.6,你和itertools模塊返回iterables的笛卡爾乘積的標準溶液:
import itertools
print list(itertools.product([1,2,3], [4,5,6]))
[(1, 4), (1, 5), (1, 6),
(2, 4), (2, 5), (2, 6),
(3, 4), (3, 5), (3, 6)]
您可以提供一個「重複」的說法與可迭代進行產品和本身:
print list(itertools.product([1,2], repeat=3))
[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
(2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
你也可以調整與組合的東西還有:
print list(itertools.combinations('123', 2))
[('1', '2'), ('1', '3'), ('2', '3')]
如果順序的問題,也有排列:
print list(itertools.permutations([1,2,3,4], 2))
[(1, 2), (1, 3), (1, 4),
(2, 1), (2, 3), (2, 4),
(3, 1), (3, 2), (3, 4),
(4, 1), (4, 2), (4, 3)]
當然所有的酷的東西不完全做同樣的事情,但你可以在某種程度上使用它們或其他解決你的問題。請記住,您可以使用list(),tuple()和set()將元組或列表轉換爲集合,反之亦然。
[Abacus github](https://github.com/foo123/Abacus)一個用於Node.JS,Python,PHP,Actionscript的組合函數庫 – 2015-03-05 23:04:49