[0, 0, [0, 0], 0, [0]]
I want to flatten a standard list that contains list irregularly like the following
[0, 0, 0, 0, 0, 0]
You could do this by listing all the values once and then applying itertools.chain.from_iterable
def flatten_sequences(sequences: List[list]) -> list:
sequences = [i if type(i) == list else [i] for i in sequences]
flattened = list(itertools.chain.from_iterable(sequences))
return flattened
Execution result
>>> flatten_sequences([0, 0, [0, 0], 0, [0]])
[0, 0, 0, 0, 0, 0]
Recommended Posts