Return equivalent of `:` from function for indexing array

前端 未结 3 775
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-21 05:03

I have a large array and a function that returns index lists into the array, i.e.,

import numpy

n = 500
a = numpy.random.rand(n)

def get_idx(k):
    # M         


        
3条回答
  •  一整个雨季
    2020-12-21 05:28

    NumPy has a helper np.s_[] which can be used to construct slice and Ellipsis objects:

    def get_idx(k):
        return np.s_[:] if k > 6 else np.s_[:k]
    
        # or even np.s_[:None if k > 6 else k]
    

    In general, a[np.s_[ ]] is exactly the same as a[ ].

提交回复
热议问题