展平列表列表 [英] Flatten list of lists
问题描述
我在 Python 中遇到方括号问题.我写了一个产生以下输出的代码:
[[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
但我想用它进行一些计算,但方括号不允许我这样做.
如何去掉括号?我看到了一些例子来做到这一点,但我无法将它们应用到这个案例中.
使用嵌套列表推导式将列表展平以去除括号".这将取消嵌套列表中存储的每个列表!
list_of_lists = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]flattened = [val for sublist in list_of_lists for val in sublist]
嵌套列表推导式的计算方式与它们展开的方式相同(即为每个新循环添加换行符和制表符.因此在这种情况下:
flattened = [val for sublist in list_of_lists for val in sublist]
相当于:
扁平化 = []对于 list_of_lists 中的子列表:对于子列表中的 val:flattened.append(val)
最大的不同在于,list comp 的计算速度比 unraveled 循环快得多,并且消除了 append 调用!
如果您在子列表中有多个项目,则列表组合甚至会将其展平.即
<预><代码>>>>list_of_lists = [[180.0, 1, 2, 3], [173.8], [164.2], [156.5], [147.2], [138.2]]>>>flattened = [val for sublist in list_of_lists for val in sublist]>>>压扁的[180.0, 1, 2, 3, 173.8, 164.2, 156.5, 147.2,138.2]I'm having a problem with square brackets in Python. I wrote a code that produces the following output:
[[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
But I would like to perform some calculations with that, but the the square brackets won't let me.
How can I remove the brackets? I saw some examples to do that but I could not apply them to this case.
Flatten the list to "remove the brackets" using a nested list comprehension. This will un-nest each list stored in your list of lists!
list_of_lists = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
flattened = [val for sublist in list_of_lists for val in sublist]
Nested list comprehensions evaluate in the same manner that they unwrap (i.e. add newline and tab for each new loop. So in this case:
flattened = [val for sublist in list_of_lists for val in sublist]
is equivalent to:
flattened = []
for sublist in list_of_lists:
for val in sublist:
flattened.append(val)
The big difference is that the list comp evaluates MUCH faster than the unraveled loop and eliminates the append calls!
If you have multiple items in a sublist the list comp will even flatten that. ie
>>> list_of_lists = [[180.0, 1, 2, 3], [173.8], [164.2], [156.5], [147.2], [138.2]]
>>> flattened = [val for sublist in list_of_lists for val in sublist]
>>> flattened
[180.0, 1, 2, 3, 173.8, 164.2, 156.5, 147.2,138.2]
这篇关于展平列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!