Here is an example to reproduce my problem:
a = np.array([[1,2], [3,4], [6,7]])
b = np.array([[1,2], [3,4], [6,7,8]])
c = np.array([[1,2], [3,4], [6]])
print(a.flatten())
print(b.flatten())
print(c.flatten())
The problem exist when one of the arrays has an item less or more.
Output:
[1 2 3 4 6 7]
[list([1, 2]) list([3, 4]) list([6, 7, 8])] # Won't work
[list([1, 2]) list([3, 4]) list([6])] # Also won't work
How I want it:
[1 2 3 4 6 7]
[1 2 3 4 6 7 8]
[1 2 3 4 6]
Does anyone know how to flatten the list properly for example b and c?
Using concatenate
np.concatenate(b)
Out[204]: array([1, 2, 3, 4, 6, 7, 8])
np.concatenate(c)
Out[205]: array([1, 2, 3, 4, 6])
You need:
from itertools import chain
a = np.array([[1,2], [3,4], [6,7]])
b = np.array([[1,2], [3,4], [6,7,8]])
c = np.array([[1,2], [3,4], [6]])
print(a.flatten())
print(list(chain(*b)))
print(list(chain(*c)))
Output:
[1 2 3 4 6 7]
[1 2 3 4 6 7 8]
[1 2 3 4 6]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.