How do I convert a tuple of tuples to a one-dimensional list using list comprehension?(如何使用列表推导将元组的元组转换为一维列表?)
问题描述
我有一个元组 - 例如:
I have a tuple of tuples - for example:
tupleOfTuples = ((1, 2), (3, 4), (5,))
我想将其转换为按顺序排列的所有元素的平面一维列表:
I want to convert this into a flat, one-dimensional list of all the elements in order:
[1, 2, 3, 4, 5]
我一直在尝试通过列表理解来实现这一点.但我似乎无法弄清楚.我能够通过 for-each 循环来完成它:
I've been trying to accomplish this with list comprehension. But I can't seem to figure it out. I was able to accomplish it with a for-each loop:
myList = []
for tuple in tupleOfTuples:
myList = myList + list(tuple)
但我觉得必须有一种方法可以通过列表理解来做到这一点.
But I feel like there must be a way to do this with a list comprehension.
一个简单的 [list(tuple) for tupleOfTuples] 只是给你一个列表列表,而不是单个元素.我想我也许可以通过使用解包运算符来解包列表,如下所示:
A simple [list(tuple) for tuple in tupleOfTuples] just gives you a list of lists, instead of individual elements. I thought I could perhaps build on this by using the unpacking operator to then unpack the list, like so:
[*list(tuple) for tuple in tupleOfTuples]
或
[*(list(tuple)) for tuple in tupleOfTuples]
...但这没有用.有任何想法吗?还是我应该坚持循环?
... but that didn't work. Any ideas? Or should I just stick to the loop?
推荐答案
通常称为扁平化嵌套结构.
it's typically referred to as flattening a nested structure.
>>> 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 作为变量名,它会影响内置.
ETA: Please don't use tuple as a variable name, it shadows built-in.
这篇关于如何使用列表推导将元组的元组转换为一维列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用列表推导将元组的元组转换为一维列表?
基础教程推荐
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 包装空间模型 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 求两个直方图的卷积 2022-01-01
