2012-02-22 98 views
8

目前,我会做:Python的组合两个for循环

for x in [1,2,3]: 
    for y in [1,2,3] 
     print x,y 

有没有做这样

for x,y in ([1,2,3],[1,2,3]): 
    print x,y 

东西想缩短这种循环的方式,这将引发“太多解压缩“异常。

回答

15

使用itertools.product

import itertools 
for x, y in itertools.product([1,2,3], [1,2,3]): 
    print x, y 

打印全部九个对:

1 1 
1 2 
1 3 
2 1 
2 2 
2 3 
3 1 
3 2 
3 3 

UPDATE:如果两个变量xy要从一个列表中选择,你可以使用repeat关键字(由agf提议):

import itertools 
for x, y in itertools.product([1,2,3], repeat=2): 
    print x, y 
+6

或'产物([1,2,3],重复= 2)'。 – agf 2012-02-22 13:00:11

+0

@agf:谢谢!我总是使用'​​product(** [1,2,3] * 2)'。我仍然可以使用我的方法,因为它更加明确,但'repeat = ...'可能更具可读性。 – ninjagecko 2012-02-22 13:27:20

+0

@ninjagecko我假设你的意思是'产品(* [[1,2,3]] * 2)',但我没有看到这更明确。正如你所示,错误也更容易。无耻的自我推销:请参阅我对[生成所有可能的三字母字符串的最佳方式是什么?](http://stackoverflow.com/a/7074066/500584) – agf 2012-02-22 16:59:52

7

你可以在用生成器表达式for循环:

for x, y in ((a,b) for a in [1,2,3] for b in [5,6,7]): 
    print x, y