列表乘法

7 投票
7 回答
7713 浏览
提问于 2025-04-15 18:41

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

[(a,a), (a,b), (a,c), (b,a), (b,b), (b,c)...] 

我试着用 L * L 这样的方法,但没有成功。有人能告诉我在 Python 中该怎么做吗?

7 个回答

7

看看这个叫做 itertools 的模块,它里面有一个功能叫 product

L =[1,2,3]

import itertools
res = list(itertools.product(L,L))
print(res)

结果是:

[(1,1),(1,2),(1,3),(2,1), ....  and so on]
22

你可以用列表推导式来实现这个功能:

[ (x,y) for x in L for y in L]

补充说明

你也可以使用itertools.product,正如其他人所建议的那样,但这只有在你使用2.6及以上版本时才可以。列表推导式在Python 2.0及以上的所有版本中都能使用。如果你选择使用itertools.product,请注意它返回的是一个生成器,而不是一个列表,所以你可能需要根据你的需求进行转换。

15

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)]

撰写回答