如何在Python中合并任意数量的元组?
我有一个元组列表:
l=[(1,2,3),(4,5,6)]
该列表可以是任意长度,元组也可以。我想将其转换为元素的列表或元组,按照它们出现的顺序:
f=[1,2,3,4,5,6] # or (1,2,3,4,5,6)
如果我知道在开发时我会返回多少个元组,我可以添加它们:
m = l[0] + l[1] # (1,2,3,4,5,6)
但是因为我不直到运行时才知道我将拥有多少元组,但我不能这样做。我觉得有一种方法可以使用 map
来做到这一点,但我无法弄清楚。我可以迭代元组并将它们添加到累加器中,但这会创建许多永远不会使用的中间元组。我还可以迭代元组,然后迭代元组的元素,并将它们附加到列表中。这看起来效率很低。也许还有一种更简单的方法,我完全掩盖了。有什么想法吗?
I have a list of tuples:
l=[(1,2,3),(4,5,6)]
The list can be of arbitrary length, as can the tuples. I'd like to convert this into a list or tuple of the elements, in the order they appear:
f=[1,2,3,4,5,6] # or (1,2,3,4,5,6)
If I know the at development time how many tuples I'll get back, I could just add them:
m = l[0] + l[1] # (1,2,3,4,5,6)
But since I don't know until runtime how many tuples I'll have, I can't do that. I feel like there's a way to use map
to do this, but I can't figure it out. I can iterate over the tuples and add them to an accumulator, but that would create lots of intermediate tuples that would never be used. I could also iterate over the tuples, then the elements of the tuples, and append them to a list. This seems very inefficient. Maybe there's an even easier way that I'm totally glossing over. Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
链接它们(仅创建一个生成器而不是保留额外的内存):
Chain them (only creates a generator instead of reserving extra memory):
对以下所有内容使用 pythonic 生成器样式:
Use the pythonic generator style for all of the following:
您可以使用
.extend()
函数将列表中的值组合起来,如下所示:或使用reduce 的更短版本:
You can combine the values in a list using the
.extend()
function like this:or a shorter version using reduce: