问题描述
所以几天前,我需要在此线程中进行特定的列表理解:
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.
所以我的问题是numpy包中是否有任何功能可以完成工作,但速度要快得多?我研究了numpy的linspace,重复,排列和内容,找不到任何突破.而且,如果有一种方法可以更快地完成工作,那么你们能告诉我方法吗?
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?
谢谢你们.
推荐答案
如果您仍然感兴趣,可以摆脱一个for
循环,并结合使用列表列表理解和numpy.hstack()
和numpy.arange()
得到想要的东西.话虽如此,我们仍然需要至少一个for
循环来完成此操作(因为range
和arange
都不接受一系列端点)
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.
这篇关于此特定清单理解的数字版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!