列表乘法
我有一个列表 L = [a, b, c] 我想生成一个元组列表:
[(a,a), (a,b), (a,c), (b,a), (b,b), (b,c)...]
我尝试做 L * L 但它不起作用。有人可以告诉我如何在 python 中得到这个吗?
I have a list L = [a, b, c] and I want to generate a list of tuples :
[(a,a), (a,b), (a,c), (b,a), (b,b), (b,c)...]
I tried doing L * L but it didn't work. Can someone tell me how to get this in python.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用列表理解来完成此操作:
edit
您也可以按照其他人的建议使用 itertools.product,但前提是您使用的是 2.6 及以上版本。列表理解适用于 2.0 以后的所有 Python 版本。如果您确实使用 itertools.product,请记住它返回一个生成器而不是列表,因此您可能需要转换它(取决于您想用它做什么)。
You can do it with a list comprehension:
edit
You can also use itertools.product as others have suggested, but only if you are using 2.6 onwards. The list comprehension will work will all versions of Python from 2.0. If you do use itertools.product bear in mind that it returns a generator instead of a list, so you may need to convert it (depending on what you want to do with it).
itertools
模块包含许多用于此类排序的有用函数的东西。您可能正在寻找产品
:The
itertools
module contains a number of helpful functions for this sort of thing. It looks like you may be looking forproduct
:看一下
itertools
模块,它提供了一个product
成员。给出:
Take a look at the
itertools
module, which provides aproduct
member.Gives:
两种主要替代方案:
前一种需要 Python 2.6 或更高版本,后者适用于您可能使用的任何 Python 版本。
Two main alternatives:
the former one needs Python 2.6 or better -- the latter works in just about any Python version you might be tied to.
x = [a,b,c]
y = []
对于 x 中的项目:
对于 x 中的第 2 项:
y.append((item, item2))
也许不是 Pythonic 方式,但可以工作
x = [a,b,c]
y = []
for item in x:
for item2 in x:
y.append((item, item2))
Maybe not the Pythonic way but working
好吧,我尝试过:
L2 = [(x,y) for x in L for x in L] 这得到了 L 平方。
这是最好的Python方式吗?我希望 L * L 能在 python 中工作。
Ok I tried :
L2 = [(x,y) for x in L for x in L] and this got L square.
Is this the best pythonic way to do this? I would expect L * L to work in python.
最老式的方法是:
它的运行时间为 O(n^2),因此相当慢,但您可以认为它是“老式”风格的代码。
The most old fashioned way to do it would be:
This has a runtime of O(n^2) and is therefore quite slow, but you could consider it to be "vintage" style code.