python - 如何使用列表推导将元组的元组转换为一维列表?

标签 python tuples list-comprehension iterable-unpacking

我有一个元组 - 例如:

tupleOfTuples = ((1, 2), (3, 4), (5,))

我想将其转换为按顺序排列的所有元素的平面一维列表:

[1, 2, 3, 4, 5]

我一直在尝试通过列表理解来实现这一点。但我似乎无法弄清楚。我能够通过 for-each 循环来完成它:

myList = []
for tuple in tupleOfTuples:
   myList = myList + list(tuple)

但我觉得必须有一种方法可以通过列表理解来做到这一点。

一个简单的 [list(tuple) for tupleOfTuples] 只是给你一个列表列表,而不是单个元素。我想我也许可以通过使用解包运算符来解包列表,如下所示:

[*list(tuple) for tuple in tupleOfTuples]

[*(list(tuple)) for tuple in tupleOfTuples]

...但这没有用。有任何想法吗?还是我应该坚持循环?

最佳答案

它通常被称为扁平化嵌套结构。

>>> tupleOfTuples = ((1, 2), (3, 4), (5,))
>>> [element for tupl in tupleOfTuples for element in tupl]
[1, 2, 3, 4, 5]

只是为了展示效率:

>>> import timeit
>>> it = lambda: list(chain(*tupleOfTuples))
>>> timeit.timeit(it)
2.1475738355700913
>>> lc = lambda: [element for tupl in tupleOfTuples for element in tupl]
>>> timeit.timeit(lc)
1.5745135182887857

ETA:请不要使用 tuple 作为变量名,它会影响内置。

关于python - 如何使用列表推导将元组的元组转换为一维列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3204245/

相关文章:

python - 在 python 中,为什么列表与列表不同[ :]?

c# - 如何分隔 C# 元组值以匹配方法参数

python - 扩展列表理解(以更好地理解它)?

python - TensorFlow 放置算法

Python 3.x tkinter : Buttons of specific shapes or Button overlay

python - 带有日期时间和日期的 Django 查询集过滤器

swift - (Swift)如何从元组数组 [(Date, MyClass)] 中获取元组元素 (Date, MyClass) 的索引?

sorting - 在 Haskell 中,如何使用内置的 sortBy 函数对对(元组)列表进行排序?

python - 可以从 Python 列表理解中捕获返回值以使用条件吗?

python - 字典中所有列表位置的总和