首页 > 其他 > 详细

展平嵌套序列

时间:2019-11-09 17:11:04      阅读:83      评论:0      收藏:0      [点我收藏+]

需求:将[1, 2, [3, 4, [5, 6], 7], 8]按顺序输出:1 2 3 4 5 6 7 8。
可以编写如下代码:

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

items = [1, 2, [3, 4, [5, 6], 7], 8]

# Produces 1 2 3 4 5 6 7 8
for x in flatten(items):
    print(x)

展平嵌套序列

原文:https://www.cnblogs.com/jeffrey-yang/p/11826443.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!