如何从Python中任意长的列表中获得叉积对列表?
示例
a = [1, 2, 3]
b = [4, 5, 6]
crossproduct(a,b)
应该会生成[[1, 4], [1, 5], [1, 6], ...]
。
发布于 2010-03-30 05:29:03
如果你使用的是Python2.6(至少),那么你正在寻找itertools.product。
>>> 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)]
发布于 2010-03-30 05:30:37
既然你要了一份清单:
[(x, y) for x in a for y in b]
但是,如果您只是通过使用生成器遍历这些列表,则可以避免列表的开销:
((x, y) for x in a for y in b)
在for
循环中的行为相同,但不会导致创建list
。
发布于 2013-11-07 17:39:34
使用生成器不需要itertools,只需:
gen = ((x, y) for x in a for y in b)
for u, v in gen:
print u, v
https://stackoverflow.com/questions/2541401
复制相似问题