列表乘法

Sch*_*tti 5 python list cartesian-product

我有一个列表L = [a,b,c],我想生成一个元组列表:

[(a,a), (a,b), (a,c), (b,a), (b,b), (b,c)...] 
Run Code Online (Sandbox Code Playgroud)

我试过做L*L但它不起作用.有人能告诉我如何在python中得到它.

Dav*_*rby 22

你可以用列表理解来做到这一点:

[ (x,y) for x in L for y in L]
Run Code Online (Sandbox Code Playgroud)

编辑

您也可以像其他人建议的那样使用itertools.product,但前提是您使用2.6以上版本.列表理解将适用于2.0的所有Python版本.如果你确实使用itertools.product,请记住它返回一个生成器而不是列表,所以你可能需要转换它(取决于你想用它做什么).


Gre*_*ill 13

itertools模块包含许多有用的功能.看起来你可能正在寻找product:

>>> import itertools
>>> L = [1,2,3]
>>> itertools.product(L,L)
<itertools.product object at 0x83788>
>>> list(_)
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
Run Code Online (Sandbox Code Playgroud)


Ale*_*ler 7

看一下itertools提供product成员的模块.

L =[1,2,3]

import itertools
res = list(itertools.product(L,L))
print(res)
Run Code Online (Sandbox Code Playgroud)

得到:

[(1,1),(1,2),(1,3),(2,1), ....  and so on]
Run Code Online (Sandbox Code Playgroud)