How to flatten a 2 deep list, return a list without any sublists within

青春壹個敷衍的年華 提交于 2021-01-28 18:37:49

问题


I was working on an algorithm that 'flattens' a list, essentially removing any sublists within a list.

For example, [2, 3, [3, 4]] should become [2, 3, 3, 4]. I wrote the following to do this:

def flatten(l):
    total = []
    for i in l:
       if i == int:
           total.append(i)
       elif i == list:
           for j in i:
               total.append(j):
    return total

This algorithm yields an error, however. If someone could help that would be great. Also, if someone could show a recursive path to solve this problem so that lists of arbitrary 'depth' can be flattened (my current algorithm can only flatten a 2D array)


回答1:


There are two major issues here - first, you aren't checking the type of the item correctly (you should use isinstace) and second you aren't calling the function recursively:

def flatten(l):
    total = []
    for i in l:
       if isinstance(i, list):
           total.extend(flatten(i))       
       else:
           total.append(i)

    return total


来源:https://stackoverflow.com/questions/50820962/how-to-flatten-a-2-deep-list-return-a-list-without-any-sublists-within

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!