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

前端 未结 11 1699
暖寄归人
暖寄归人 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 23:13

    The answer is quite simple. Take advantage of recursion.

    def flatten(nst_lst, final_list):
    
        for val in nst_lst:
            if isinstance(val, list):
                flatten(val, final_list)
            else:
                final_list.append(val)
        return final_list
    
    #Sample usage
    fl_list = []
    lst_to_flatten = [["this",["a",["thing"],"a"],"is"],["a","easy"]]
    
    print(flatten(lst_to_flatten, fl_list))
    

提交回复
热议问题