Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

python - Return equivalent of `:` from function for indexing array

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):
    # More complicated in reality
    return range(n) if k > 6 else range(k)

data = a[get_idx(29)]
data = a[get_idx(30)]
# ...

A typical case is that the range is the entire array, range(n). Unfortunately, a[range(n)] scales with n while a[:] is of course constant-time. It's a pity that one cannot return : from get_idx.

What can I return from get_idx to use as an index for the entire array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...