flatten list in python

semms like generator  is more efficient


Python

[edit]Recursive

Function flatten is recursive and preserves its argument:

>>> def flatten(lst):
	return sum( ([x] if not isinstance(x, list) else flatten(x)
		     for x in lst), [] )
 
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>> flatten(lst)
[1, 2, 3, 4, 5, 6, 7, 8]

[edit]Non-recursive

Function flat is iterative and flattens the list in-place. It follows the Python idiom of returning None when acting in-place:

>>> def flat(lst):
    i=0
    while i<len(lst):
        while True:
            try:
                lst[i:i+1] = lst[i]
            except (TypeError, IndexError):
                break
        i += 1
 
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>> flat(lst)
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8]

[edit]Generative

This method shows a solution using Python generators.

flatten is a generator that yields the non-list values of its input in order. In this case, the generator is converted back to a list before printing.

>>> def flatten(lst):
     for x in lst:
         if isinstance(x, list):
             for x in flatten(x):  ### *Note* this needed when recursively  call, you can't just flatten(x) 
                 yield x           ###  invoke generator in generator
         else:
             yield x
 
 
>>>lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>>print list(flatten(lst)) 
[1, 2, 3, 4, 5, 6, 7, 8]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值