2012-08-15 105 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