3 Jul 2013

Flatten List列表快速展开

收藏到CSDN网摘


python中有时候list会多层嵌套,需要展开成一维列表,最快速的方法是使用yield生成器.
但是针对一层嵌套的[[a,b,c],[d,e]]这种,sum(L,[])还是最快的.


====================
更新: 最简短的代码:
flat_list=lambda t:sum(([x]if not isinstance(x,list)else flat_list(x)for x in t),[])
====================

def flat(s):
    for item in s:
        if isinstance(item,list):
            for subitem in flat(item):
                yield subitem
        else:
            yield item

def checkio(data):
    return [x for x in flat(data)]

#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio([1, 2, 3]) == [1, 2, 3], 'First example'
    assert checkio([1, [2, 2, 2], 4]) == [1, 2, 2, 2, 4], 'Second example'
    assert checkio([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) \
           == [2, 4, 5, 6, 6, 6, 6, 6, 7], 'Third example'

No comments :

Post a Comment