目标:使用 Python3 将具有 N 个嵌套列表的数组转换为一维数组。
数组示例:
ND_array = [1, [2, 3], [4, [5, 6]], 7, [8, 9, [10, 11, 12, [13, [14, 15, 16], 17], 18], 19, 20], 21]
将示例数组转换为以下结果:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
不受原始数组维数限制的最优解。
适用于 Python 中任何 N 维数组的一个简单易用的解决方案是利用递归。
oneD_array = []
def transform_array(arr):
for x in arr:
if type(x) == list:
transform_array(x)
else:
oneD_array.append(x)
return oneD_array
ND_array = [1, [2, 3], [4, [5, 6]], 7, [8, 9, [10, 11, 12, [13, [14, 15, 16], 17], 18], 19, 20], 21]
print(transform_array(ND_array))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
版本 2.0:与上面相同的输出
def transform_array(arr, oneD_array):
for x in arr:
if isinstance(x, list):
transform_array(x, oneD_array)
else:
oneD_array.append(x)
return oneD_array