gpt4 book ai didi

分解元组列表的 pythonic 方法

转载 作者:太空狗 更新时间:2023-10-29 22:00:54 26 4
gpt4 key购买 nike

我需要做相反的事情

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))

但我想看一些更奇特的东西。

最佳答案

最有效的方法是这样的:

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

总结:小列表的求和速度更快,但大列表的性能会显着下降。

关于分解元组列表的 pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1880683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com