2012-08-15 104 views
4

說我有3個不同的變量,每個都有2個可能的值,所以總共有8種不同的組合。有沒有python庫函數,或者我可以用來打印所有可能的組合的算法?打印所有組合,python

感謝

+0

[Python中的可能重複代碼從列表中挑選出所有可能的組合?](http:// stackoverflow .com/questions/464864/python-code-to-pick-out-all-possible-combinations-from-a-list) – 2012-08-15 11:55:16

+0

@MattFenwick:不,這不是一個組合問題,而是它正在尋找的產品對於。 – 2012-08-15 12:01:44

+1

[在Python中獲取一系列列表的笛卡爾積]的可能副本(http://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists-in- python) – 2012-08-15 12:02:36

回答

11

我認爲你正在尋找product

a = [1, 2] 
b = [100, 200] 
c = [1000, 2000] 

import itertools 
for p in itertools.product(a, b, c): 
    print p 

打印:

(1, 100, 1000) 
(1, 100, 2000) 
(1, 200, 1000) 
(1, 200, 2000) 
(2, 100, 1000) 
(2, 100, 2000) 
(2, 200, 1000) 
(2, 200, 2000) 
+0

謝謝你!正是我需要的 – Yotam 2012-08-15 12:21:47