Return equivalent of `:` from function for indexing array

前端 未结 3 778
爱一瞬间的悲伤
爱一瞬间的悲伤 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:17

    Have a look at slice

    def get_x():
        return slice(2)
    
    a=list(range(100))
    a[get_x()]
    

    will return [0, 1]

    UPDATE

    And for your need get_x function should be

    def get_x(k, n):
        return slice(n if k > 6 else k)
    

    Update

    as @Eric correctly noted it's better to pass None instead of n. So function would be:

    def get_x(k):
        return slice(None if k > 6 else k)
    

提交回复
热议问题