我有一个列表列表,例如
[
[1, 2, 3],
[4, 5, 6],
[7],
[8, 9]
]
如何将其弄平以获得 [1,2,2,3,4,5,6,7,8,9]
?
如果您的列表来自嵌套列表的理解,则可以通过修复理解力来更简单/直接解决该问题;请参阅我如何从列表理解而不是嵌套列表中获得平坦的结果?。
这里最受欢迎的解决方案通常只会使嵌套列表的一个“级别”变平。参见平列列表列表的不规则(任意嵌套)列表对于完全嵌入深度嵌套结构的解决方案(一般而言,一般而言)。 /sub>
I have a list of lists like
[
[1, 2, 3],
[4, 5, 6],
[7],
[8, 9]
]
How can I flatten it to get [1, 2, 3, 4, 5, 6, 7, 8, 9]
?
If your list of lists comes from a nested list comprehension, the problem can be solved more simply/directly by fixing the comprehension; please see How can I get a flat result from a list comprehension instead of a nested list?.
The most popular solutions here generally only flatten one "level" of the nested list. See Flatten an irregular (arbitrarily nested) list of lists for solutions that completely flatten a deeply nested structure (recursively, in general).
发布评论
评论(30)
名为
XSS
的列表可以使用嵌套列表理解:以上等效于:
这是相应的函数:
这是最快的方法。
作为证据,使用
timeit
timeit 标准中的模块库,我们会看到:说明:基于
+
的方法(包括sum
中的隐含用途)是必要的,o(l ** 2)< /code>当有l子列表时 - 随着中级结果列表的越来越长,在每个步骤中,新的中间结果列表对象都会分配,并且必须复制上一个中级结果中的所有项目(以及一些(以及一些)最终添加了新的)。因此,为简单起见,没有实际的一般性丧失,请假设您有每个项目的子列表。 -2
次,依此类推;副本的总数是x的x总和,x的总和从1到l排除,即,m*(l ** 2)/2
。列表理解只会生成一个列表,一次将每个项目(从其原始的居住地到结果列表)都精确地复制。
A list of lists named
xss
can be flattened using a nested list comprehension:The above is equivalent to:
Here is the corresponding function:
This is the fastest method.
As evidence, using the
timeit
module in the standard library, we see:Explanation: the methods based on
+
(including the implied use insum
) are, of necessity,O(L**2)
when there are L sublists -- as the intermediate result list keeps getting longer, at each step a new intermediate result list object gets allocated, and all the items in the previous intermediate result must be copied over (as well as a few new ones added at the end). So, for simplicity and without actual loss of generality, say you have L sublists of M items each: the first M items are copied back and forthL-1
times, the second M itemsL-2
times, and so on; total number of copies is M times the sum of x for x from 1 to L excluded, i.e.,M * (L**2)/2
.The list comprehension just generates one list, once, and copies each item over (from its original place of residence to the result list) also exactly once.
您可以使用
itertools.chains.chain()
:或者您可以使用
itertoolss.chain.from_iterables.chain.from_iterable()代码>
不需要用
*
运算符解开列表:此方法可以说是比
[sublist in l for sublist中的lim s for sublist in in sublist中的项目]
并且似乎也更快:You can use
itertools.chain()
:Or you can use
itertools.chain.from_iterable()
which doesn't require unpacking the list with the*
operator:This approach is arguably more readable than
[item for sublist in l for item in sublist]
and appears to be faster too:作者的注释:这非常效率低下。但是很有趣,因为 monoids 很棒。
sum
总和峰值xss
,并将第二个参数用作总和的初始值[]
。 (默认的初始值是0
,不是列表。)由于您要求和列表,因此您实际上获得
[1,3]+[2,4]
>由于sum([[1,3],[2,4]],[])
等于[1,3,2,4]
。请注意,仅在列表列表上工作。对于列表列表的列表,您需要另一个解决方案。
Note from the author: This is very inefficient. But fun, because monoids are awesome.
sum
sums the elements of the iterablexss
, and uses the second argument as the initial value[]
for the sum. (The default initial value is0
, which is not a list.)Because you are summing nested lists, you actually get
[1,3]+[2,4]
as a result ofsum([[1,3],[2,4]],[])
, which is equal to[1,3,2,4]
.Note that only works on lists of lists. For lists of lists of lists, you'll need another solution.
我用),发现
是最快的解决方案,当许多小列表和很少的长列表被加入时。 (
operator.iadd
同样快。)一个更简单且可接受的变体是,
如果统一的数量较大,则其性能比上述建议差一些。
代码重现图:
I tested most suggested solutions with perfplot (a pet project of mine, essentially a wrapper around
timeit
), and foundto be the fastest solution, both when many small lists and few long lists are concatenated. (
operator.iadd
is equally fast.)A simpler and also acceptable variant is
If the number of sublists is large, this performs a little worse than the above suggestion.
Code to reproduce the plot:
使用 XS 添加到下一个列表
ys
:输出:
使用
operator.concat
:输出:输出:
Using
functools.reduce
, which adds an accumulated listxs
to the next listys
:Output:
A faster way using
operator.concat
:Output:
这是一种适用于嵌套和混合容器的对象(例如数字 )的一般方法。这可能会使简单和复杂的容器变平(另请参见 emo )。
代码
注释:
flatten(x)
可以替换flatten(x)中的sub_x的:sub_x
collection.abc
移动键入
模块。demo
参考
Here is a general approach that applies to objects (e.g. numbers, strings) in nested and mixed containers. This can flatten both simple and complicated containers (see also Demo).
Code
Notes:
yield from flatten(x)
can replacefor sub_x in flatten(x): yield sub_x
collection.abc
to thetyping
module.Demo
Reference
要使一个深层嵌套的数据实现,请使用
iteratory_utilitys_utilitys。 deepflatten
1 :它是一个生成器,因此您需要将结果施加到
list
或明确迭代它。要使一个级别的级别弄平,如果每个项目本身都具有峰值,则还可以使用
iteration_utilities.flatten
本身只是itertools.chain.from_iterable
:只是添加一些时间(基于 nicoschlömer的答案不包括此答案中呈现的功能):
这是一个日志图,可容纳跨越庞大的值。对于定性推理:较低是更好的。
结果表明,如果峰值仅包含几个内部迭代物品,则
sum
将是最快的,但是对于长期迭代而言,仅itertools.chains.chain.from_iterable
,iteration_utilities。 DeepFlatten
或嵌套的理解性具有合理的性能,itertools.chain.from_iterable
是最快的(正如NicoSchlömer已经注意到的那样)。1免责声明:我是该图书馆的作者
To flatten a data-structure that is deeply nested, use
iteration_utilities.deepflatten
1:It's a generator so you need to cast the result to a
list
or explicitly iterate over it.To flatten only one level and if each of the items is itself iterable you can also use
iteration_utilities.flatten
which itself is just a thin wrapper arounditertools.chain.from_iterable
:Just to add some timings (based on Nico Schlömer's answer that didn't include the function presented in this answer):
It's a log-log plot to accommodate for the huge range of values spanned. For qualitative reasoning: Lower is better.
The results show that if the iterable contains only a few inner iterables then
sum
will be fastest, however for long iterables only theitertools.chain.from_iterable
,iteration_utilities.deepflatten
or the nested comprehension have reasonable performance withitertools.chain.from_iterable
being the fastest (as already noticed by Nico Schlömer).1 Disclaimer: I'm the author of that library
以下对我来说似乎最简单:
The following seems simplest to me:
考虑安装
more_itertools
软件包。
它带有( source a href =“ https://docs.python.org/3/library/itertools.html#itertools-recipes” rel =“ noreferrer”> itertools配方):
注意:注意:注意: a href =“ https://more-itertools.readthedocs.io/en/stable/pi.html#more_itertools.flatten” rel =“ noreferrer”> docs ,
flatten
需要一个列表列表。请参阅下面的关于更加不规则输入的内容。在版本2.4时,您可以使用
more_itertools.collapse
( source ,由abarnet贡献)。Consider installing the
more_itertools
package.It ships with an implementation for
flatten
(source, from the itertools recipes):Note: as mentioned in the docs,
flatten
requires a list of lists. See below on flattening more irregular inputs.As of version 2.4, you can flatten more complicated, nested iterables with
more_itertools.collapse
(source, contributed by abarnet).根据您的列表
[[1,2,3],[4,5,6],[7],[8,9]]
是1个列表级别,我们可以简单地使用sum(list,[])
,无需使用任何库时,就可以扩展此方法的优势。只需通过
map
添加每个元素的映射函数在这里,关于这种方法的记忆,对缺点有一个明确的解释。简而言之,它递归创建列表对象,应避免使用:(
According your list
[[1, 2, 3], [4, 5, 6], [7], [8, 9]]
which is 1 list level, we can simply usesum(list,[])
without using any librariesTo extend the advantage of this method when there is a tuple or number existing inside. Simply adding a mapping function for each element by
map
to the listIn here, there is a clear explanation of the drawback in terms of memory for this approach. In short, it recursively creates list objects, which should be avoided :(
您的函数无法使用的原因是,扩展 将数组在就位且不会返回。您仍然可以使用这样的东西从lambda返回X:
注意:扩展比列表上的 + + + +更有效。
The reason your function didn't work is because the extend extends an array in-place and doesn't return it. You can still return x from lambda, using something like this:
Note: extend is more efficient than + on lists.
matplotlib.cbook.flatten()
即使它们比示例更深,它们也将适用于嵌套列表。结果:
这比下划线快18倍._。扁平:
matplotlib.cbook.flatten()
will work for nested lists even if they nest more deeply than the example.Result:
This is 18x faster than underscore._.flatten:
一个人还可以使用numpy的
flat当标准师具有相同维度时的作品。
One can also use NumPy's flat:
It only works when sublists have identical dimensions.
您可以使用
list
扩展
方法。它表明是最快的:性能:
输出:
You can use the
list
extend
method. It shows to be the fastest:Performance:
Output:
有几个答案,具有与下面相同的递归插入方案的答案,但是没有一个使用
尝试
,这使得解决方案更健壮, pythonic 。用法:这是一个生成器,通常您想将其包装在可观的构建器中在循环的
中。
该解决方案的优点是:
nb:由于 all aterables被扁平,因此将字符串分解为序列单个字符。如果您不喜欢/想要这样的行为,则可以使用以下版本,这些版本从字符串和字节(例如字符串和字节)中过滤出来:
There are several answers with the same recursive appending scheme as below, but none makes use of
try
, which makes the solution more robust and Pythonic.Usage: this is a generator, and you typically want to enclose it in an iterable builder like
list()
ortuple()
or use it in afor
loop.Advantages of this solution are:
N.B.: Since all iterables are flattened, strings are decomposed into sequences of single characters. If you don't like/want such behavior, you can use the following version which filters out from flattening iterables like strings and bytes:
注意:以下适用于Python 3.3+,因为它使用
fard_from
。
六个
也是第三方软件包,尽管它是稳定的。或者,您可以使用sys.version
。对于
obj = [[1,2,],[3,4],[5,6]]
,这里的所有解决方案都很好,包括列表理解和itertools .chain.from_iterable
。但是,请考虑以下更复杂的情况:
这里有几个问题:
6
,只是标量;这是不可能的,因此以上路线将在这里失败。'abc'
,是在技术上迭代的(所有str
s is)。但是,在两行之间读取一点,您不想将其视为这样 - 您想将其视为单个元素。[8,[9,10]]
本身就是一个嵌套的迭代性。基本列表理解和链。from_iterable
仅提取“ 1级别”。您可以按照以下方式进行纠正:
在这里,您检查子元素(1)是否可以使用
iToble
,来自itertools
的ABC,但也希望确保(2)元素是 not> not “类似字符串”。Note: Below applies to Python 3.3+ because it uses
yield_from
.six
is also a third-party package, though it is stable. Alternately, you could usesys.version
.In the case of
obj = [[1, 2,], [3, 4], [5, 6]]
, all of the solutions here are good, including list comprehension anditertools.chain.from_iterable
.However, consider this slightly more complex case:
There are several problems here:
6
, is just a scalar; it's not iterable, so the above routes will fail here.'abc'
, is technically iterable (allstr
s are). However, reading between the lines a bit, you don't want to treat it as such--you want to treat it as a single element.[8, [9, 10]]
is itself a nested iterable. Basic list comprehension andchain.from_iterable
only extract "1 level down."You can remedy this as follows:
Here, you check that the sub-element (1) is iterable with
Iterable
, an ABC fromitertools
, but also want to ensure that (2) the element is not "string-like."如果您愿意放弃少量的速度以使外观更清洁,则可以使用
numpy.concatenate()。tolist()
或numpy.concatenate()。ravel()。 .tolist()
:您可以在文档中找到更多信息, numpy.concatenate 和。
If you are willing to give up a tiny amount of speed for a cleaner look, then you could use
numpy.concatenate().tolist()
ornumpy.concatenate().ravel().tolist()
:You can find out more here in the documentation, numpy.concatenate and numpy.ravel.
我想要一个可以处理多个嵌套的解决方案(
[[1],[[[2]],[3]]],[1,2,3]
),但也会不要递归(我有很大的递归水平,并且有递归错误。这就是我想到的:
和测试:
I wanted a solution which can deal with multiple nesting (
[[1], [[[2]], [3]]], [1, 2, 3]
for example), but would also not be recursive (I had a big level of recursion and I got a recursion error.This is what I came up with:
and tests:
这可能不是最有效的方法,但我认为放置了一个单线(实际上是两线线)。这两个版本都将在任意层次结构列表上使用,并利用语言功能(Python&nbsp; 3.5)和递归。
输出是以
一种深度的初步方式起作用。递归降低直到找到非上列元素,然后扩展局部变量
flist
,然后将其滚动给父。每当返回flist
时,它将扩展到列表理解中的父flist
。因此,在根本上,返回平面列表。以上一个创建了几个本地列表并返回用于扩展父列表的这些列表。我认为这可能是创建Gloabl
flist
,如下所示。输出又是又一次。
尽管我目前不确定效率,但
This may not be the most efficient way, but I thought to put a one-liner (actually a two-liner). Both versions will work on arbitrary hierarchy nested lists, and exploits language features (Python 3.5) and recursion.
The output is
This works in a depth first manner. The recursion goes down until it finds a non-list element, then extends the local variable
flist
and then rolls back it to the parent. Wheneverflist
is returned, it is extended to the parent'sflist
in the list comprehension. Therefore, at the root, a flat list is returned.The above one creates several local lists and returns them which are used to extend the parent's list. I think the way around for this may be creating a gloabl
flist
, like below.The output is again
Although I am not sure at this time about the efficiency.
如果您想毫不掩饰所有内容并保留不同的元素列表,则也可以使用它。
If you want to unnest everything and keep a distinct list of elements, you could use this as well.
这是我在其他答案中没有看到的一种方法。它支持任何层次的嵌套,迭代和无库的工作:
Here's an approach I didn't see in the other answers. It supports any level of nesting, works iteratively and without libraries:
我建议使用具有产量语句的发电机和的产量。
这是一个例子:
I would suggest using generators with a yield statement and yield from.
Here's an example:
另一种适用于异性和同质整数列表的不寻常方法:
Another unusual approach that works for hetero- and homogeneous lists of integers:
一个非恢复功能,可以使任何深度列表的列表更平坦:
A non-recursive function to flatten lists of lists of any depth:
不是一个单线,但是在这里看到所有答案,我想这个长列表错过了一些模式匹配,所以:)
这两种方法可能不是有效的,但是无论如何,它很容易阅读(至少对我来说;也许我被功能编程所宠坏了):
第二版认为列表的列表列表...嵌套是什么:
Not a one-liner, but seeing all the answers here, I guess this long list missed some pattern matching, so here it is :)
The two methods are probably not efficient, but anyway, it's easy to read (to me at least; perhaps I'm spoiled by functional programming):
The second version considers lists of lists of lists... whatever the nesting:
如果您有一个numpy数组
a
:生产:
np.flatten
还接受其他参数:c
:f
fk
有关参数的更多详细信息在这里。
If you have a numpy array
a
:produces:
np.flatten
also accepts other parameters:C
:F
A
K
More details about parameters are available here.
如果我想在以前的出色答案中添加一些东西,这是我的递归
扁平
函数,它不仅可以弄平嵌套列表,还可以弄平任何给定的容器或任何可以抛出项目的任何对象。这也适用于任何嵌套深度,它是一个懒惰的迭代器,可根据要求产生项目:这样,您可以排除不想被扁平的类型,例如
str
或其他什么。这个想法是,如果对象可以传递
iter()
准备就可以产生项目。因此,峰值可以将发电机表达式作为项目。有人可以争论:当OP不要求它时,为什么要写这件事?好,你是对的。我只是觉得这可能会帮助某人(就像我自己一样)。
测试用例:
输出:
If I want to add something to the great previous answers, here is my recursive
flatten
function which can flatten not only nested lists, but also any given container or any generally any object which can throw out items. This does also work for any depth of nesting and it is a lazy iterator which yields the items as requested:This way, you can exclude types you don't want to be flattened, like
str
or what else.The idea is if an object can pass the
iter()
it's ready to yield items. So the iterable can have even generator expressions as an item.Someone could argue: Why did you write this that generic when the OP didn't ask for it? OK, you're right. I just felt like this might help someone (like it did for myself).
Test cases:
Output:
这使用
parsel.utils.flatten
,这在变平多个列表嵌套方面非常好。我发现避免开销 numpy 。我将在此处使用数字来简单起见,但是我主要将其与字符串一起使用,这是为了我的目的,它很快就可以使用(每个嵌套的列表,每个元素约40个元素)。
This uses
parsel.utils.flatten
which is great when it comes to flattening multiple levels of list nesting. I found it useful to avoid overhead of NumPy.I'll use numbers here for the purpose of simplicity, but but I predominantly used it with strings, which worked pretty fast for my purposes (200 nested lists with each about 40 elements).
我喜欢添加一个高性能的生成器解决方案,该解决方案可以使的任何深度不(只有二维列表)添加嵌套列表(或任何类型的峰值):
根据您的需求,生成器具有巨大的优势列表。例如,如果要添加
filter()
之后功能。最终的列表应仅在构造完整发电机含量之后的结尾进行实例。通过这种过滤,您可以避免对项目进行多次迭代。备注:与其他提出的发电机解决方案相比,这是一种迭代而不是递归解决方案,可以避免在深嵌套的迭代物体的情况下避免递归词。
I like to add a high performant generator solution which can fatten nested lists (or any kind of iterable) of any depth not (only two-dimensional-lists):
Depending on your needs a generators have huge advantages over lists. E.g. If you want add
filter()
functions afterwards. The resulting list should be instanced only at the end after you have constructed the full generator incl. the filtering by this you avoid multiple iterations over the items.Remark: Compared to the other proposed generator solution this is an iterative and not a recursive solution which avoids RecursionErrors in case of deep nested iterables.