如何在 Python 中合并任意数量的元组? [英] How To Merge an Arbitrary Number of Tuples in Python?

查看:65
本文介绍了如何在 Python 中合并任意数量的元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元组列表:

l=[(1,2,3),(4,5,6)]

列表可以是任意长度,元组也可以.我想按照它们出现的顺序将其转换为元素的列表或元组:

f=[1,2,3,4,5,6] # 或 (1,2,3,4,5,6)

如果我在开发时知道我会返回多少个元组,我可以添加它们:

m = l[0] + l[1] # (1,2,3,4,5,6)

但是因为直到运行时我才知道我将拥有多少个元组,所以我不能这样做.我觉得有一种方法可以使用 map 来做到这一点,但我想不通.我可以遍历元组并将它们添加到累加器中,但这会创建许多永远不会使用的中间元组.我还可以遍历元组,然后是元组的元素,并将它们附加到列表中.这似乎非常低效.也许有一种更简单的方法可以让我完全掩饰.有什么想法吗?

解决方案

链接他们 (只创建一个生成器而不是保留额外的内存):

<预><代码>>>>从 itertools 导入链>>>l = [(1,2,3),(4,5,6)]>>>列表(chain.from_iterable(l))[1, 2, 3, 4, 5, 6]

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?

解决方案

Chain them (only creates a generator instead of reserving extra memory):

>>> from itertools import chain
>>> l = [(1,2,3),(4,5,6)]
>>> list(chain.from_iterable(l))
[1, 2, 3, 4, 5, 6]

这篇关于如何在 Python 中合并任意数量的元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆