How to flatten a hetrogenous list of list into a single list in python?

前端 未结 11 1732
暖寄归人
暖寄归人 2020-12-01 22:59

I have a list of objects where objects can be lists or scalars. I want an flattened list with only scalars. Eg:

L = [35,53,[525,6743],64,63,[743,754,757]]
ou         


        
11条回答
  •  旧时难觅i
    2020-12-01 23:15

    Here's a oneliner, based on the question you've mentioned:

    list(itertools.chain(*((sl if isinstance(sl, list) else [sl]) for sl in l)))
    

    UPDATE: And a fully iterator-based version:

    from itertools import imap, chain
    list(chain.from_iterable(imap(lambda x: x if isinstance(x, list) else [x], l)))
    

提交回复
热议问题