python 扁平化处理嵌套型的序列

2022-05-17  本文已影响0人  孙广宁
4.14 如何处理有嵌套型的数据
>>> from collections import Iterable
>>> def f(items,ignore_type=(str,bytes)):
...     for x in items:
...         if isinstance(x,Iterable) and not isinstance(x,ignore_type):
...             yield from f(x)
...         else:
...             yield x
...
>>> items=[1,2,[3,4,[5,6],7],8]
>>> for x in f(items):
...     print(x)
...
1
2
3
4
5
6
7
8
>>>
上一篇 下一篇

猜你喜欢

热点阅读