我正在研究numpy来管理不同的数组。我有一个python函数返回给我这个数组的数组:
res = [[[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]]]
我想从这个res
变量中提取的是这个:
a = [1 2 1 2 1 2 1 2 1 2]
b = [5 6 5 6 5 6 5 6 5 6]
c = [7 8 7 8 7 8 7 8 7 8]
思路是提取并合并每个数组的第一个数组到a
,第二个数组到b
,依此类推。
你能帮我实现这个结果吗?非常感谢!
您可以使用numpy.hstack
然后使用元组解包。
In [7]: a, b, c = np.hstack(res)
In [8]: a
Out[8]: array([1, 2, 1, 2, 1, 2, 1, 2, 1, 2])
In [9]: b
Out[9]: array([5, 6, 5, 6, 5, 6, 5, 6, 5, 6])
In [10]: c
Out[10]: array([7, 8, 7, 8, 7, 8, 7, 8, 7, 8])
给定:
import numpy as np
res = np.array([[[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]]])
a = res[:, 0]
b = res[:, 1]
c = res[:, 2]
print(a)
print(b)
print(c)
输出:
[[1 2]
[1 2]
[1 2]
[1 2]
[1 2]]
[[5 6]
[5 6]
[5 6]
[5 6]
[5 6]]
[[7 8]
[7 8]
[7 8]
[7 8]
[7 8]]
或:
print(a.flatten())
print(b.flatten())
print(c.flatten())
输出:
[1 2 1 2 1 2 1 2 1 2]
[5 6 5 6 5 6 5 6 5 6]
[7 8 7 8 7 8 7 8 7 8]