如何压缩两个列表列表
我有两个具有相同数量项目的列表。这两个列表如下所示:
L1 = [[1, 2], [3, 4], [5, 6]]
L2 =[[a, b], [c, d], [e, f]]
我正在创建一个如下所示的列表:
Lmerge = [[1, 2, a, b], [3, 4, c, d], [5, 6, e, f]]
我试图使用 zip()
类似这样的东西:
for list1, list2 in zip(*L1, *L2):
Lmerge = [list1, list2]
组合两个列表列表的最佳方式是什么?提前致谢。
I have two lists of lists that have equivalent numbers of items. The two lists look like this:
L1 = [[1, 2], [3, 4], [5, 6]]
L2 =[[a, b], [c, d], [e, f]]
I am looking to create one list that looks like this:
Lmerge = [[1, 2, a, b], [3, 4, c, d], [5, 6, e, f]]
I was attempting to use zip()
something like this:
for list1, list2 in zip(*L1, *L2):
Lmerge = [list1, list2]
What is the best way to combine two lists of lists? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
或者,
或者,
我们也可以在没有
zip()
的情况下做到这一点:一些基准
以下是迄今为止提供的答案的一些基准。
看起来最流行的答案(
[x + y for x,y in zip(L1,L2)]
)与@hammar 的map
解决方案。另一方面,我给出的替代解决方案已被证明是垃圾!但是,最快的解决方案(目前)似乎是使用列表理解而不使用 zip() 的解决方案。
@Zac 的建议非常快,但是我们在这里比较苹果和橙子,因为它在
L1
上进行了就地列表扩展,而不是创建第三个列表。因此,如果不再需要L1
,这是一个很好的解决方案。但是,如果
L1
必须保持完整,那么一旦包含深度复制,性能就会低于标准。Or,
or,
We can also do it without
zip()
:Some benchmarks
Here are some benchmarks for the answers provided so far.
It looks like the most popular answer (
[x + y for x,y in zip(L1,L2)]
) is pretty much on par with @hammar'smap
solution.On the other hand, the alternative solutions I've given have proven to be rubbish!However, the fastest solutions (for now) seems to be the ones that uses list comprehension without
zip()
.@Zac's suggestion is really quick, but then we're comparing apples and oranges here since it does a list extension in-place on
L1
instead of creating a third list. So, ifL1
is not longer needed, this is a great solution.However, if
L1
has to be kept intact, then performance would be sub par once you include the deepcopy.您想要将子列表与加号运算符组合起来,并在列表理解中迭代它们:
You want to combine the sublists with the plus operator, and iterate over them in a list comprehension: