• python压平嵌套列表


    list 是 Python 中使用最频繁的数据类型, 标准库里面有丰富的函数可以使用。
    不过,如果把多维列表转换成一维列表(不知道这种需求多不多),还真不容易找到好用的函数,
    要知道Ruby、Mathematica、Groovy中可是有flatten的啊。
    如果列表是维度少的、规则的,还算好办
    例如:

    li=[[1,2],[3,4],[5,6]]
    print ([j for i in li for j in i])
    #or
    from itertools import chain
    print (list(chain(*li)))
    #or
    a=[[1,2],[3,4],[5,6]]
    t=[]
    [t.extend(i) for i in a]
    print (t)
    #or
    print (sum(li,[]))

    对于复杂一些的,如:li=[1,[2],[[3]],[[4,[5],6]]],上面的方法就不好使了,得换个方法了,
    从结构上看像是树状的,很容易联想到了目录的遍历,于是就有了下面的做法:

    def flat(tree):
        res = []
        for i in tree:
            if isinstance(i, list):
                res.extend(flat(i))
            else:
                res.append(i)
        return res

    另一种思路,嵌套列表无非就是有很多成对的方括号,一维的列表只有一对,把中间的去掉就行了,转换为字符串就好办了:

    def flatten(seq):
        s=str(seq).replace('[', '').replace(']', '') #当然也可以用正则
        return [eval(x) for x in s.split(',') if x.strip()]

    不过,这种做法对于列表中出现包含"["或"]"的字符串时就无能为力了,需要改进。

    出处:http://www.cnblogs.com/c-hy/archive/2012/09/21/2696703.html

  • 相关阅读:
    PHP快速排序算法
    PHP选择排序算法
    php几个常用的概率算法(抽奖、广告首选)
    免费Git客户端:sourcetree详细介绍
    apidoc @apiGroup兼容中文
    PHP中的精确计算bcadd,bcsub,bcmul,bcdiv 及 扩展安装
    mysql-表分区
    mysql表优化
    MySQL执行计划extra中的using index 和 using where using index 的区别
    mysql-锁
  • 原文地址:https://www.cnblogs.com/jingsupo/p/10097855.html
Copyright © 2020-2023  润新知