# 将不规则的Python多维数组拉平到一维的方法实现

### 原始需求：

l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

l = [[1, 2], [3, 4], [5, [6, 7, [8, 9]]], 10, [11, [12, 13, [14, 15, [16]]]]]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

### 使用numpy拉平数组

import numpy as np
np.array(l).flatten().tolist()

[1, 2, 3, 4, 5, 6, 7, 8, 9]

### 使用python拉平数组

l = [[1, 2, 3], [4, 5], [6, 7], [8, 9, 10, 11]]
np.array(l).flatten().tolist()

D:\Anaconda3\lib\site-packages\ipykernel_launcher.py:2: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray

[[1, 2, 3], [4, 5], [6, 7], [8, 9, 10, 11]]

import itertools
list(itertools.chain(*l))

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

sum(l, [])

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

result = []
for i in l:
result += i
result

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

### 将不规则多维数组拉平到1维

l = [[1, 2], [3, 4], [5, [6, 7, [8, 9]]], 10, [11, [12, 13, [14, 15, [16]]]]]
l

[[1, 2], [3, 4], [5, [6, 7, [8, 9]]], 10, [11, [12, 13, [14, 15, [16]]]]]

list_str = str(l).replace("[", "").replace("]", "")
eval(f"[{list_str}]")

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

import re
eval(re.sub("(?!^)\[|\](?!\$)", "", str(l)))

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

### 深度优先遍历策略拉平多维数组

def flatten(items, result=[]):
for item in items:
if isinstance(item, list):
flatten(item, result)
else:
result.append(item)

result = []
flatten(l, result)
result

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

def flatten(items):
for item in items:
if isinstance(item, list):
yield from flatten(item)
else:
yield item

result = [e for e in flatten(l)]
result

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

from collections import deque

stack = deque(l)
result = []
while len(stack) != 0:
item = stack.popleft()
if isinstance(item, list):
for e in reversed(item):
stack.appendleft(e)
else:
result.append(item)
result

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

from collections import deque

stack = l.copy()
result = deque()
while len(stack) != 0:
item = stack.pop()
if isinstance(item, list):
for e in item:
stack.append(e)
else:
result.appendleft(item)
result = list(result)
result

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]