Convert multi-dimensional list to a 1D list in Python

前端 未结 7 683
萌比男神i
萌比男神i 2020-12-05 00:14

A multidimensional list like l=[[1,2],[3,4]] could be converted to a 1D one by doing sum(l,[]). Can anybody please explain how that happens?

<
7条回答
  •  自闭症患者
    2020-12-05 00:42

    For any kind of multidiamentional array, this code will do flattening to one dimension :

    def flatten(l):
        try:
            return flatten(l[0]) + (flatten(l[1:]) if len(l) > 1 else []) if type(l) is list else [l]
        except IndexError:
            return []
    

提交回复
热议问题