python implements two methods of tiling nested lists
- 2021-01-25 07:48:55
- OfStack
Approach 1: Use a list derivation
>>> vec = [[1,2,3],[4,5,6],[7,8,9]]
>>> get = [num for elem in vec for num in elem]
>>> get
[1, 2, 3, 4, 5, 6, 7, 8, 9]
The method is equivalent to
>>> vec = [[1,2,3],[4,5,6],[7,8,9]]
>>> result = []
>>> for elem in vec:
for num in elem:
result.append(num)
>>> result
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 2:
Use the sum function
>>> vec = [[1,2,3],[4,5,6],[7,8,9]]
>>> get = sum(vec,[])
>>> get
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Or use the chain function
>>> vec = [[1,2,3],[4,5,6],[7,8,9]]
>>> from itertools import chain
>>> list(chain(*vec))
[1, 2, 3, 4, 5, 6, 7, 8, 9]