问题
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