Sometimes you want to convert a 2D list to a 1D list in Python.
It can be converted in one line by using the sum
function.
If you don't know it, you won't know what you're doing at first glance, but it's surprisingly convenient to use.
If you want to convert a 3D list to a 1D list, you can use the sum
function twice.
x = [[1, 2], [3, 4]]
x = sum(x, [])
print(x) # [1, 2, 3, 4]
y = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
y = sum(sum(y, []), [])
print(y) # [1, 2, 3, 4, 5, 6, 7, 8]
Use itertools.chain.from_iterable () for speed.
This is faster than using the sum
function.
import itertools
x = [[1, 2], [3, 4]]
x = itertools.chain.from_iterable(x)
print(list(x)) # [1, 2, 3, 4]
y = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
y = itertools.chain.from_iterable(list(itertools.chain.from_iterable(y)))
print(list(y)) # [1, 2, 3, 4, 5, 6, 7, 8]
In addition to the above, you can also create your own function. It does not depend on the number of dimensions in the list, so it is recommended when handling data with various dimensions.
https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists
Recommended Posts