将数组拆分为非递减数组

时间:2019-03-17 14:01:03

标签: python numpy

我正在尝试将给定数组拆分为非递减数组,而不使用for循环或使用np.diff。我想知道是否可以使用np.where来做到这一点,但无法想象如何在不循环的情况下做到这一点。

1 个答案:

答案 0 :(得分:2)

这是使用numpy的一种方式:

#include <regex>
#include <string>
#include <iostream>

int main() {
    std::regex reg(R"((?:^|[^\\])(?:\\{2})*\[([^\][\\]*(?:\\[\s\S][^\][\\]*)*)\])");
    std::string s("Some text [my \\[ value \\] here] and here");
    std::smatch matches;
    if (std::regex_search(s, matches, reg)) {
        std::cout<<matches.str(1);                 // => my \[ value \] here
    }
    return 0;
}

让我们检查一些随机数组:

def split_increasing(x):
    # Check if following value is greater
    ix = np.greater(a[:-1], a[1:])
    # Use the indices where the above is True
    # to split the array
    return np.split(a, np.flatnonzero(ix)+1)

输出

a = np.random.randint(1,20,10)
# array([12, 15,  3,  7, 18, 18,  9, 16, 15, 19])
split_increasing(a)
相关问题