def flatten(L):
for item in L:
try:
yield from flatten(item)
except TypeError:
yield item
list(flatten([[[1, 2, 3], [4, 5]], 6]))
>>>[1, 2, 3, 4, 5, 6]
from typing import Iterable
# flatten any number of nested iterables (lists, tuples)
def flatten_iterables(iterable: Iterable) -> list:
"""Convert iterables (lists, tuples) to list (excluding string and dictionary)
Args:
iterables (Iterable): Iterables to flatten
Returns:
list: return a flattened list
"""
lis = []
for i in iterable:
if isinstance(i, Iterable) and not isinstance(i, str):
lis.extend(flatten_iterables(i))
else:
lis.append(i)
return lis
>>> a = np.array([[1,2], [3,4]])
>>> a.flatten()
array([1, 2, 3, 4])
>>> a.flatten('F')
array([1, 3, 2, 4])