我们可以使用递归函数来处理这个问题。递归函数可以在不知道嵌套深度的情况下处理任意维度的列表或数组。
以下是Python示例代码:
def flatten(l, n):
"""
将嵌套n层的列表或数组转换为扁平列表
:param l: 原始列表或数组
:param n: 最多嵌套层数
:return: 扁平列表
"""
if n == 0:
return l
flattened = []
for item in l:
if isinstance(item, (list, tuple)):
flattened += flatten(item, n-1)
else:
flattened.append(item)
return flattened
示例输入:
array = [[1, 2], [3], [[4, 5, [6], [[[7]]], 8], 9]]
n = 4
示例输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
在上面的示例中,我们将一个嵌套4层的列表转换为了一个扁平列表。