checkio任务之python3:合并一个嵌套的list

Flatten a List

def flat_list(array):
    """
    方法一:采用生成器的方式
    """
    # def process(array):
    #     if isinstance(array, list):
    #         for sublist in array:
    #             for item in process(sublist):
    #                 yield item
    #     else:
    #         yield array
    # data = list(process(array))
    # return data
    """
    方法二:采用递归的方式,判断类型,添加到新的list
    """
    r = []
    def f(l):
        for i in l:
            r.append(i) if type(i) is int else f(i)
    f(array)
    return r

"""
方法三:看不懂的大神写法,等我再想想。
"""
#flat_list = f = lambda d: [d] if int == type(d) else sum(map(f, d), [])


if __name__ == '__main__':
    assert flat_list([1, 2, 3]) == [1, 2, 3], "First"
    assert flat_list([1, [2, 2, 2], 4]) == [1, 2, 2, 2, 4], "Second"
    assert flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) == [2, 4, 5, 6, 6, 6, 6, 6, 7], "Third"
    assert flat_list([-1, [1, [-2], 1], -1]) == [-1, 1, -2, 1, -1], "Four"
    print('Done! Check it')

你可能感兴趣的:(python3-note)