Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的成对叉积_Python_List - Fatal编程技术网

Python中的成对叉积

Python中的成对叉积,python,list,Python,List,如何从Python中任意长的列表中获取交叉乘积对列表 例子 crossproduct(a,b)应该产生[[1,4],[1,5],[1,6],…]如果您使用(至少)Python2.6,那么您需要的是[[1,4],[1,5],[1,6],…] >>> import itertools >>> a=[1,2,3] >>> b=[4,5,6] >>> itertools.product(a,b) <itertools.prod

如何从Python中任意长的列表中获取交叉乘积对列表

例子
crossproduct(a,b)
应该产生
[[1,4],[1,5],[1,6],…]

如果您使用(至少)Python2.6,那么您需要的是
[[1,4],[1,5],[1,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)]
导入itertools >>>a=[1,2,3] >>>b=[4,5,6] >>>itertools.产品(a、b) >>>列表(itertools.产品(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
循环中的行为相同,但不会导致使用生成器创建
列表

不需要itertools,只需:

gen = ((x, y) for x in a for y in b)

for u, v in gen:
    print u, v

请注意,对于2.6版本之前的版本,您只需从链接文档中复制并粘贴纯Python实现。
product()
不限于两个参数,因此也可用于任意数量的列表(列表本身)。因此,您可以执行
列表(itertools.product(*[[1,2]、[3,4]、[5,6]])
以获得
[(1,3,5)、(1,3,6),…
它被称为笛卡尔积。也被称为叉积。我更喜欢这种方法,但不知道为什么。可能是因为双循环是显式的?很好的pythonic。或者正如我喜欢说的,是pythontificity的一个很好的例子。谢谢!我非常喜欢看起来像它的代码。我不确定你的确切意思。如果
a
ad
b
不是集合,并且它们本身具有重复的元素,那么是的,这会产生重复的条目。
[(x,y)对于[1,1]中的x,对于[2]中的y]
会产生
[(1,2)、(1,2)]
。但这是在非集合输入上应用集合上定义的数学运算的结果。不会出现反向对-
a
iterable中的任何内容都不会显示为返回对的第二个元素,除非该元素也在
b
iterable中。显式总是优于隐式。
gen = ((x, y) for x in a for y in b)

for u, v in gen:
    print u, v