Python中 展开嵌套的序列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010339879/article/details/81433218

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: [email protected]
@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=' ')
二.总结

还是比较实用的一个功能,一个列表嵌套 很多层,通过这个生成器函数, 就可以轻松解决,把数据放在同一层上了.


分享快乐,留住感动.2018-08-05 17:26:53 –frank

猜你喜欢

转载自blog.csdn.net/u010339879/article/details/81433218