Skip to content

Commit b82ebd8

Browse files
committed
flatten
1 parent 406159c commit b82ebd8

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

flatten.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
例子卡片7:嵌套数组完全展开
2+
3+
对于如下数组:
4+
5+
```
6+
[[[1,2,3],[4,5]]]
7+
```
8+
9+
如何完全展开成一维的。这个小例子实现的`flatten`是递归版,两个参数分别表示带展开的数组,输出数组。
10+
11+
```python
12+
from collections.abc import *
13+
14+
# 返回list
15+
def flatten(input_arr, output_arr=None):
16+
if output_arr is None:
17+
output_arr = []
18+
for ele in input_arr:
19+
if isinstance(ele, Iterable): # 判断ele是否可迭代
20+
flatten(ele, output_arr) # 尾数递归
21+
else:
22+
output_arr.append(ele) # 产生结果
23+
return output_arr
24+
```
25+
26+
调用`flatten`:
27+
28+
```
29+
print(flatten([[1,2,3],[4,5]]))
30+
print(flatten([[1,2,3],[4,5]], [6,7]))
31+
print(flatten([[[1,2,3],[4,5,6]]]))
32+
# 结果:
33+
[1, 2, 3, 4, 5]
34+
[6, 7, 1, 2, 3, 4, 5]
35+
[1, 2, 3, 4, 5, 6]
36+
```
37+
38+
numpy里的`flatten`与上面的函数实现有些微妙的不同:
39+
40+
```
41+
import numpy
42+
b = numpy.array([[1,2,3],[4,5]])
43+
b.flatten()
44+
array([list([1, 2, 3]), list([4, 5])], dtype=object)
45+
```
46+
47+
你看还是与我们小例子中的不太一样吧。
48+

0 commit comments

Comments
 (0)