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

前端 未结 11 1731
暖寄归人
暖寄归人 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:06

    Here is a relatively simple recursive version which will flatten any depth of list

    l = [35,53,[525,6743],64,63,[743,754,757]]
    
    def flatten(xs):
        result = []
        if isinstance(xs, (list, tuple)):
            for x in xs:
                result.extend(flatten(x))
        else:
            result.append(xs)
        return result
    
    print flatten(l)
    

提交回复
热议问题