Python中的成对交叉产品
如何从Python中的任意长列表中获得交叉产品对的列表?
例
a = [1, 2, 3] b = [4, 5, 6] 
  crossproduct(a,b)应该产生[[1, 4], [1, 5], [1, 6], ...] 。 
你正在寻找itertools.product,如果你(至less)Python 2.6。
 >>> import itertools >>> a=[1,2,3] >>> b=[4,5,6] >>> itertools.product(a,b) <itertools.product object at 0x10049b870> >>> list(itertools.product(a,b)) [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)] 
既然你问了一个清单:
 [(x, y) for x in a for y in b] 
但是,如果您只是通过使用生成器来循环访问,则可以避免列表的开销:
 ((x, y) for x in a for y in b) 
 在for循环中的行为相同,但不会导致创buildlist 。 
使用生成器不需要itertools,只需:
 gen = ((x, y) for x in a for y in b) for u, v in gen: print u, v