如何在不相等的部分中拆分数组?

Rub*_*iqs 0 python arrays numpy

我有这样的数组

import numpy as np

x = np.array([1, 2, 3, 99, 99, 3, 2, 1])
Run Code Online (Sandbox Code Playgroud)

我想将它分成三部分

x1 = array([1, 2, 3])
x2 = array([99, 99])
x3 = array([3, 2, 1])
Run Code Online (Sandbox Code Playgroud)

做这个的最好方式是什么?

Cle*_*leb 5

你可以使用np.split:

x = np.array([1, 2, 3, 99, 99, 3, 2, 1])

x1, x2, x3 = np.split(x, [3, 5])
Run Code Online (Sandbox Code Playgroud)

[3, 5] 从而指定要拆分的索引.

产量

x1
array([1, 2, 3])

x2
array([99, 99])

x3
array([3, 2, 1])
Run Code Online (Sandbox Code Playgroud)