python技巧:拆分多层嵌套列表

方法一:

>>> import itertools
>>> a = [[1, 2], [3, 4], [5, 6]]
>>> list(itertools.chain.from_iterable(a))
[1, 2, 3, 4, 5, 6]

方法二:

from collections import Iterable

# return list
def flatten(input_arr, output_arr=None):
    if output_arr is None:
        output_arr = []
    for ele in input_arr:
        if isinstance(ele, Iterable):
            flatten(ele, output_arr)    #tail-recursion
        else:
            output_arr.append(ele)      #produce the result
    return output_arr
posted @ 2018-07-11 22:09  bingo彬哥  阅读(3576)  评论(0编辑  收藏  举报
本站总访问量