Is there any easy way to flatten
import numpy
np.arange(12).reshape(3,4)
Out[]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11
I have a solution that doesn't involve numpy if you want, and it will take care for every kind of array you'll get,
[[12312],[],[[]]]
[[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]
[-1, [1, [-2], 1], -1]
etc
First option(won't work for strings)
def flat_list(array):
return list(flatten(array))
def flatten(nested):
try:
for sublist in nested:
for element in flatten(sublist):
yield element
except TypeError:
yield nested
Second option:
def flatten(nested): #in case you got strings and you want to avoide an infinite recursion
try:
# Don't iterate over string-like objects:
try: nested + ''
except TypeError: pass
else: raise TypeError
for sublist in nested:
for element in flatten(sublist):
yield element
except TypeError:
yield nested