说我有一个清单t = list(i for i in np.arange(0.5,10.5,0.5)).我想找到的索引位置s=[3,5,7]内t.我知道我可以通过t.index(s)循环来做到这一点,但有更优雅的方式吗?
重要的是要意识到你总是需要一些循环.即使t.index是一个循环,它只是隐藏它!但是据我所知,Python标准库中没有任何函数可以避免显式循环s.
然而,人们可以提高效率(我的意思是效率更高[t.index(needle) for needle in s])!特别是如果您的列表已排序.
你已经习惯了NumPy,np.searchsorted肯定会很快:
import numpy as np
t = np.arange(0.5,10.5,0.5)
s = [3, 5, 7]
np.searchsorted(t, s)
Run Code Online (Sandbox Code Playgroud)
如果你想留在Python中,还有一个bisect模块,它至少可以节省一些(隐式)循环:
from bisect import bisect_left
def index(a, x): # Taken from the bisect documentation
'Locate the leftmost value exactly equal to x'
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError
indices = [index(t, needle) for needle in s]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |