def flattenList(toFlatten):
final=[]
for el in toFlatten:
if isinstance(el, list):
final.extend(flattenList(el))
else:
final.append(el)
return final
当我不知道列表将嵌套多深时,这是我能想到的唯一方法。
你应该避免在 Python 中进行类型检查。在这种情况下,这意味着要避免按类型区分的任意嵌套结构。您可以构建自己的节点类型,您可以通过类型检查以外的方法对其进行遍历,例如查看特定属性。
对于展平一个级别或恰好 n 个级别,请查看itertools.chain.from_iterable
.
我不知道您所说的“功能性”是什么意思。这段代码非常实用:它使用递归(不值得称赞!)并且它不会改变它的参数。(严格来说,它确实使用可变状态来构建列表,但这就是你在 Python 中的做法。
我想还有一个功能属性是惰性评估。你可以这样实现
def flatten(toFlatten):
for item in toFlatten:
if isinstance(item, list): # Ewww, typchecking
for subitem in flatten(item): # they are considering adding
yield subitem # "yield from" to the language
# to give this pattern syntax
else:
yield item
递归在 Python 中非常有限(至少在其所有主要实现中),通常应该避免任意深度。很可能重写这个(以及所有递归代码)以使用迭代,这将使它更具可扩展性(并且功能更少,这在 Python 中是一件好事,它并不特别适合 FP。)
这个答案解释了为什么你不想reduce
在 Python 中使用它。
考虑片段
reduce(operator.add, [[1], [2], [3], [4], [5]])
这有什么关系?
[1] + [2] => [1, 2]
[1, 2] + [3] => This makes a new list, having to go over 1, then 2, then 3. [1, 2, 3]
[1, 2, 3] + [4] => This has to copy the 1, 2, and 3 and then put 4 in the new list
[1, 2, 3, 4] + [5] => The length of stuff I have to copy gets bigger each time!
这种二次行为是完全可以避免的:原始解决方案(以及任何数量的其他解决方案)不会形成这些中间复制步骤。
在itertools的文档下,有一个flatten()
功能
这是另一种选择(尽管可能有比类型检查更干净的东西,例如测试某些东西是否可迭代,因此不是“原子”):
def flatten(lst):
if not isinstance(lst,list):
return [lst]
else:
return reduce(lambda x,y:x+y,[flatten(x) for x in lst],[])
它基于类似方案的东西。