Ruby's Array Class includes the method 'flatten', which creates a one-dimensional array out of an array consisting of subarrays of various depths. For instance the array
a = [ 1, 2, [3, 4, [5, 6], 7], 8], 9 ]
when flattened
a.flatten
becomes the one-dimensional array
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
It's also possible to limit the depth of the stacked subarrays. If you only want to flatten 1 level down, the array
a = [ 1, 2, [3, 4, [5, 6], 7], 8], 9 ]
when flattened
a.flatten( 1 )
becomes
[ 1, 2, 3, 4, [5, 6], 7, 8, 9 ]
Unfortunately, there is no such builtin method in python, so I had to write my own, which implements the ruby behaviour:
def flatten( array, level=-1 ):
flat = []
for item in array:
if( level == -1 and isinstance( item, list ) ):
flat.extend( flatten( item, level ) )
elif( level > 0 and isinstance( item, list ) ):
flat.extend( flatten( item, level - 1 ) )
else:
flat.append( item )
return flat
Example
>>> a = [ 1, 2, [3, 4, [5, 6], 7], 8], 9 ]
>>> flatten(a)
>>> [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
>>> flatten( a, 1 )
>>> [ 1, 2, 3, 4, [5, 6], 7, 8, 9 ]