3 ms·
Some python 2 def flatten(x): def flatten_generator(x): if type(x) == list: for y in x: for z in fl
by andr3w321 10y ago
Some python 2
def flatten(x):
def flatten_generator(x):
if type(x) == list:
for y in x:
for z in flatten(y):
yield z
else:
yield x
return list(flatten_generator(x))
assert(flatten([1, [2,3]]) == [1,2,3])
ary = [1, [2,3], [4, [5,6]]]
print flatten(ary)
- falcolas 10y agoI'd personally change `if type(x) == list` to `if isinstance(x, (list, tuple, set))` to catch all common iterables and their subclasses.