Possible duplicate:
Smooth (irregular) list of lists in Python
I'm having trouble using python to recursively smooth the list. I have seen several methods that require an understanding of lists and various methods that require import, however I am looking for a very simple method for recursively smoothing a list of different depths that also does not use any loops. I had a series of tests, but there are two that I cannot pass
flatten([[[[]]], [], [[]], [[], []]]) # empty multidimensional list
flatten([[1], [2, 3], [4, [5, [6, [7, [8]]]]]]) # multiple nested list
My code
def flatten(test_list):
if len(test_list) == 0:
return []
elif isinstance(test_list,list) and type(test_list[0]) in [int,str]:
return [test_list[0]] + flatten(test_list[1:])
elif isinstance(test_list,list) and isinstance(test_list[0],list):
return test_list[0] + flatten(test_list[1:])
else:
return flatten(test_list[1:])
I would appreciate some advice.
source
share