pythonic方式爆炸元组列表

时间:2009-12-10 12:31:24

标签: python list

我需要做与此相反的事情

Multiple Tuple to Two-Pair Tuple in Python?

即,我有一个元组列表

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

需要制作此

[1,2,3,4,5,6]

我个人会这样做

>>> tot = []
>>> for i in [(1,2), (3,4), (5,6)]:
...     tot.extend(list(i))

但是我希望看到一些比较漂亮的东西。

3 个答案:

答案 0 :(得分:20)

最有效的方法是:

tuples = [(1,2), (3,4), (5,6)]
[item for t in tuples for item in t]

输出

[1, 2, 3, 4, 5, 6]

以下是the comparison我在重复的问题中以各种方式做到了。

我知道有人会建议这个解决方案

sum(tuples, ())

但是不要使用它,它会为每一步创建一个新的中间结果列表!除非你不关心性能,只想要一个紧凑的解决方案。 有关详细信息,请查看Alex's answer

总结:小型列表的总和更快,但使用更大的列表时性能会显着下降。

答案 1 :(得分:6)

>>> import itertools
>>> tp = [(1,2),(3,4),(5,6)]
>>> lst = list(itertools.chain(*tp))
>>> lst
[1, 2, 3, 4, 5, 6]

当然,如果您不需要列表而是迭代器,则可以放弃list()转换调用。

答案 2 :(得分:2)

l = [(1,2), (3,4), (5,6)]
reduce (lambda x,y: x+list(y), l, [])