Skip to content

Commit 4fc6b52

Browse files
committed
add a traversal func
1 parent f5febd5 commit 4fc6b52

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

traversal.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# -*- coding: utf-8 -*-
2+
'''
3+
from collections import Iterable
4+
def flat(items, L=None):
5+
if L is None:
6+
L = []
7+
for item in items:
8+
if isinstance(item, Iterable):
9+
return flat(item, L)
10+
else:
11+
L.append(item)
12+
13+
return L
14+
15+
if __name__ == "__main__":
16+
items = [1, 2, [3, 4, [5, 6, 7], 8, 9]]
17+
new_items = flat(items)
18+
print(new_items)
19+
'''
20+
from collections import Iterable
21+
def flat(items, ignore_types=(str, bytes)):
22+
'''
23+
http://python3-cookbook.readthedocs.io/zh_CN/latest/c04/p14_flattening_nested_sequence.html
24+
'''
25+
for item in items:
26+
if isinstance(item, Iterable) and not isinstance(item, ignore_types):
27+
yield from flat(item)
28+
else:
29+
yield item
30+
31+
if __name__ == "__main__":
32+
items = [1, 2, [3, 4, [5, 6, 7], 8], 9]
33+
for i in flat(items):
34+
print(i)

0 commit comments

Comments
 (0)