简体   繁体   中英

Numpy version of this particular list comprehension

So a few days ago I needed a particular list comprehension in this thread: Selecting a subset of integers given two lists of end points

and I got a satisfying answer. Fast forward now, I somehow need to boost the performance, as what I am working with involves looping it and in each iterations the lengths of these end-point arrays are at least few thousands.

So my question is is there any functions in numpy package that can get the job done but a lot faster? I've looked into numpy's linspace, repeat, arange and stuff, and couldn't find any breakthrough. And if there is a way to get the job done faster, can you guys show me the way?

Thank you guys in advance.

If it is still of interest to you, you could get rid of one for loop and use numpy.arange() in combination with list comprehension and numpy.hstack() to get what is desired. Having said that we would still need at least one for loop to get this done (because neither range nor arange accept a sequence of endpoints)

t1 = [0,13,22]
t2 = [4,14,25]
np.hstack([np.arange(r[0], r[1]+1)  for r in zip(t1, t2)])

# outputs
array([ 0,  1,  2,  3,  4, 13, 14, 22, 23, 24, 25])

However, I don't know how much more performant this is going to be for your specific case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM