在没有循环的情况下,在python中返回列表索引的优雅方法是什么?

A11*_*122 4 python list

说我有一个清单t = list(i for i in np.arange(0.5,10.5,0.5)).我想找到的索引位置s=[3,5,7]内t.我知道我可以通过t.index(s)循环来做到这一点,但有更优雅的方式吗?

MSe*_*ert 5

重要的是要意识到你总是需要一些循环.即使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)

  • 如果你真的想得到花哨的东西(并且我想指的是过早优化),你也可以对针列表进行排序,然后将先前找到的索引(递增1)作为`lo`参数传递给`bisect_left`. (2认同)