拼合名单列表 [英] Flatten list of lists

查看:75
本文介绍了拼合名单列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用方括号在Python中的一个问题。我写了一个code产生的输出如下:

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.

推荐答案

平展列表中的删除括号的使用嵌套列表COM prehension。这将取消窝储存在你的名单列表中的每个列表!

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]

嵌套列表的COM prehensions中相同的方式,它们解开评估(即添加新行和标签为每个新的循环因此,在这种情况下:

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]

相当于:

flattened = []
for sublist in list_of_lists:
    for val in sublist:
        flattened.append(val)

最大的区别是,列表补偿评估MUCH比拆开的循环更快,消除了追加来电!

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆