4.14 展开嵌套的序列
一 问题
如果有一个列表里面有嵌套列表,如果把它展开在同一个列表中的呢?
参考文档
https://python3-cookbook.readthedocs.io/zh_CN/latest/c04/p14_flattening_nested_sequence.html
1 如果有一个序列 会嵌套另一个序列, 然后里面又有嵌套另外一个序列,
你想把他们展开, 放在同一层上面
比如这是一个列表
items = [1, 2, [3, 4, [5, ('hello', 'frank', ['aaa', 'bbb', 'ccc']), 6], 7], 8]
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
""" @author: Frank @contact: frank.chang@shoufuyou.com @file: test_flatten.py @time: 2018/8/5 下午4:14 https://python3-cookbook.readthedocs.io/zh_CN/latest/c04/p14_flattening_nested_sequence.html """
from collections import Iterable
def flatten(items, ignore_types=(str, bytes)):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types):
yield from flatten(x)
else:
yield x
if __name__ == '__main__':
items = [1, 2, [3, 4, [5, ('hello', 'frank', ['aaa', 'bbb', 'ccc']), 6], 7], 8]
for i in items:
print(i)
# Produces 1 2 3 4 5 hello frank aaa bbb ccc 6 7 8
for x in flatten(items):
print(x, end=' ')
二.总结
<center>还是比较实用的一个功能,一个列表嵌套 很多层,通过这个生成器函数, 就可以轻松解决,把数据放在同一层上了.
分享快乐,留住感动.2018-08-05 17:26:53 –frank
</center>