且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

给定起始位置和结束位置列表构造 Numpy 索引

更新时间:2022-06-15 09:51:26

我会使用

np.r_[tuple(slice(s, e) for s, e in zip(start, end))]

这是一个不使用 Python 循环的解决方案:

Here is a solution that does not use a Python loop:

def indices(start, end):
    lens = end - start
    np.cumsum(lens, out=lens)
    i = np.ones(lens[-1], dtype=int)
    i[0] = start[0]
    i[lens[:-1]] += start[1:]
    i[lens[:-1]] -= end[:-1]
    np.cumsum(i, out=i)
    return i

这只会创建一个临时 NumPy 数组 (lens),并且比任何其他解决方案都快得多.

This only creates a single temporary NumPy array (lens) and is much faster than any of the other solutions.