Saturday, October 25, 2008

99 problems - python - 7

Flatten a nested list structure.

import types
def flatten_list(lst):
if type(lst) not in (list, tuple, types.GeneratorType):
yield lst
for x in lst:
for _x in flatten_list(x):
yield _x

I'm being a little loose with the definition of a list here but I think this a behavior I would want from a function like this. Call it as list(flatten_list(my_list)) to get an actual list.

Something doesn't sit quite right with me about that nested for statement. Maybe something more elegant will come to me later.

No comments: