关于列表的扁平化

Python2

from compiler.ast import flatten

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

In [3]: flatten(a)

Out[3]: [1, 2, 3, 4, 5, 6, 7, 8, 9]



In [4]: a=[[1,2,3],[4],[5,[6]],[7,8,9]]
In [5]: flatten(a)
Out[5]: [1, 2, 3, 4, 5, 6, 7, 8, 9]



In [7]: a=[[1,2,3],[4,5],[6],7]
In [8]: flatten(a)
Out[8]: [1, 2, 3, 4, 5, 6, 7]



python3

In [1]: a=[[1,2,3],[4,5,6],[7,8,9]]
In [2]: sum(a,[])
Out[2]: [1, 2, 3, 4, 5, 6, 7, 8, 9]


In [1]: from functools import reduce
In [2]: a=[[1,2,3],[4,5,],[6]]
In [3]: a=reduce(lambda x,y:x+y,a)
In [4]: a
Out[4]: [1, 2, 3, 4, 5, 6]


上面方法可能只对二层列表有效。除了应用已经封装的方法函数,自己可以写一个函数

Python3


alist = [[[12, 34, [15]], 2], [5], [6,9], 7]
blist = []


def spre_list(rlist):
    for i in rlist:

        if isinstance(i, list):
            spre_list(i)
        else:
            blist.append(i)


if __name__ == '__main__':
    spre_list(alist)
    print(blist)  # [12, 34, 15, 2, 5, 6, 9, 7]

没有更多推荐了,返回首页