是的,我知道这个主题之前已经被讨论过了:
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
这是最好的方法吗?我是不是忽略了什么?任何问题吗?
不使用实例的简单函数
L = [[[1, 2, 3], [4, 5]], 6]
l1 = []
def FlattenList(List1):
for i in range(len(List1)):
if type(List1[i]) == type([]):
FlattenList(List1[i])
else:
l1.append(List1[i])
return l1
FlattenList(L)
[1, 2, 3, 4, 5, 6]
不使用实例的简单函数
L = [[[1, 2, 3], [4, 5]], 6]
l1 = []
def FlattenList(List1):
for i in range(len(List1)):
if type(List1[i]) == type([]):
FlattenList(List1[i])
else:
l1.append(List1[i])
return l1
FlattenList(L)
[1, 2, 3, 4, 5, 6]
@unutbu的非递归解决方案的生成器版本,由@Andrew在评论中要求:
def genflat(l, ltypes=collections.Sequence):
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], ltypes):
if not l[i]:
l.pop(i)
i -= 1
break
else:
l[i:i + 1] = l[i]
yield l[i]
i += 1
这个生成器的简化版本:
def genflat(l, ltypes=collections.Sequence):
l = list(l)
while l:
while l and isinstance(l[0], ltypes):
l[0:1] = l[0]
if l: yield l.pop(0)