美文网首页
嵌套list的展开python

嵌套list的展开python

作者: 钢筋铁骨 | 来源:发表于2020-04-15 01:35 被阅读0次

eg:
input:[1, 3,[5, 6, [9, 10], [11,[12, [13, 14]]], 15]]
output:[1, 3, 5, 6, 9, 10, 11, 12, 13, 14, 15]

class FlatList(object):
    def __init__(self):
        self.res = []

    def run(self, big_list):
        if not isinstance(big_list, list):
            return
        for item in big_list:
            if isinstance(item, list):
                self.run(item)
            else:
                self.res.append(item)

    def flat(self, l):
        for k in l:
            if isinstance(k, list):
                for x in self.flat(k):
                    yield x
                # 等价于
                # yield from self.flat(k)
            else:
                yield k


big_list = [1, 3,[5, 6, [9, 10], [11,[12, [13, 14]]], 15]]

print ("原始list:")
print (big_list)
s = FlatList()
s.run(big_list=big_list)
print ("result: ", s.res)
print ("yield写法:", list(s.flat(big_list)))
···

相关文章

  • 嵌套list的展开python

    eg:input:[1, 3,[5, 6, [9, 10], [11,[12, [13, 14]]], 15]]o...

  • 8、Python列表

    上集回顾: Python函数 while循环嵌套 Python列表(list)是一种有序的集合,是 Python ...

  • 嵌套式List comprehension

    上一节《Python优雅的递推式构造列表(List comprehension)》 本节介绍Nested(嵌套式)...

  • Python list 生成式(推导式list comprehe

    在list生成式中嵌套if else 如果按中文习惯写嵌套列表生成式可能写出如下的错误语法 Python的语法是按...

  • Python 如何展开嵌套的序列

    问题[https://www.bilibili.com/video/BV1LZ4y1H75S] 你想将一个多层嵌套...

  • Python3 - 展开嵌套的序列

    问题 将一个多层嵌套的序列展开成一个单层列表 解决方案 可以写一个包含 yield from 语句的递归生成器来轻...

  • list和tuple

    list:[ ] 关键词:[ ]、列表、集合、有序、可变、可嵌套、索引 Python内置的一种数据类型是列表:li...

  • python面试常用算法

    展开嵌套的list 快速排序 艾氏筛法求质数 求大于n的最小整数 不用循环和条件打印1~1000 不同范围的随机数...

  • python 字典dict 操作方法

    dict()的操作方法 嵌套 嵌套在list中也存在,就是元素是list,在dict中,也有类似的样式: 获取键、...

  • python面试常用算法

    展开嵌套的list 艾氏筛法求质数 求大于n的最小整数 不用循环和条件打印1~1000 不同范围的随机数转换 有两...

网友评论

      本文标题:嵌套list的展开python

      本文链接:https://www.haomeiwen.com/subject/ignfvhtx.html