是的,我知道这个主题之前已经被讨论过了:
Python成语链(扁平化)有限迭代对象的无限迭代?
在Python中扁平化一个浅列表
理解平展一个序列的序列吗?
我如何从列表的列表中创建一个平面列表?
但据我所知,所有的解决方案,除了一个,在像[[[1,2,3],[4,5]],6]这样的列表上失败,其中期望的输出是[1,2,3,4,5,6](或者更好,一个迭代器)。
我看到的唯一解决方案,适用于任意嵌套是在这个问题:
def flatten(x):
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(el)
return result
这是最好的方法吗?我是不是忽略了什么?任何问题吗?
我是一个愚蠢的人,所以我会给出一个“愚蠢”的解决方案。所有的递归都伤了我的大脑。
flattened_list = []
nested_list = [[[1, 2, 3], [4, 5]], 6]
def flatten(nested_list, container):
for item in nested_list:
if isintance(item, list):
flatten(item, container)
else:
container.append(item)
>>> flatten(nested_list, flattened_list)
>>> flattened_list
[1, 2, 3, 4, 5, 6]
我知道这是一个副作用但这是我对递归的最好理解
大多数答案都使用循环遍历条目。这里我有一个使用EAFP方法的变体:尝试在输入上获得一个迭代器,如果成功,首先在第一个元素上运行函数,然后在这个迭代器的其余部分上运行。如果你不能得到迭代器,或者它是一个字符串或字节对象:产生元素。
感谢A. Kareem的建议,他发现我的代码非常慢,因为对字符串和字节对象的递归花费了太长时间,这里是我的代码的改进版本。
def flatten(x, it = None):
try:
if type(x) in (str, bytes):
yield x
else:
if not it:
it = iter(x)
yield from flatten(next(it))
if type(x) not in (str, bytes):
yield from flatten(x, it)
except StopIteration:
pass
except Exception:
yield x
oldlist = [1,[[[["test",3]]]],((4,5,6)),[ bytes("test", encoding="utf-8"),7,[8,9]]]
newlist = [ x for x in flatten(oldlist) ]
print(newlist)
# [1, 'test', 3, 4, 5, 6, b'test', 7, 8, 9]
你可以使用第三方包iteration_utilities中的deepflatten:
>>> from iteration_utilities import deepflatten
>>> L = [[[1, 2, 3], [4, 5]], 6]
>>> list(deepflatten(L))
[1, 2, 3, 4, 5, 6]
>>> list(deepflatten(L, types=list)) # only flatten "inner" lists
[1, 2, 3, 4, 5, 6]
它是一个迭代器,所以你需要迭代它(例如用列表包装它或在循环中使用它)。在内部,它使用迭代方法而不是递归方法,并且它是作为C扩展编写的,因此它可以比纯python方法更快:
>>> %timeit list(deepflatten(L))
12.6 µs ± 298 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>> %timeit list(deepflatten(L, types=list))
8.7 µs ± 139 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>> %timeit list(flatten(L)) # Cristian - Python 3.x approach from https://stackoverflow.com/a/2158532/5393381
86.4 µs ± 4.42 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit list(flatten(L)) # Josh Lee - https://stackoverflow.com/a/2158522/5393381
107 µs ± 2.99 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit list(genflat(L, list)) # Alex Martelli - https://stackoverflow.com/a/2159079/5393381
23.1 µs ± 710 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
我是iteration_utilities库的作者。
我试过不使用任何库来解决它。只需使用两个嵌套函数即可。
def first(list_to_flatten):
a = []
def second(list_to_flatten):
for i in list_to_flatten:
if type(i) is not list:
a.append(i)
else:
list_to_flatten = i
second(list_to_flatten)
second(list_to_flatten)
return a
list_to_flatten = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]
a = first(list_to_flatten)
print(a)
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]