What is an elegant way to return a list index in python without looping?

Say I have a list t = list(i for i in np.arange(0.5,10.5,0.5)). I want to find index positions s=[3,5,7]inside t. I understand that I can do this through a loop t.index(s), but is there a more elegant way?

+4
source share
1 answer

It’s important to understand that you always need loops. Even t.indexmakes a loop, it just hides it from you! However, as far as I know, no function in the Python standard library escapes an explicit loop over s.


However, you can make it more effective (I mean more effective than [t.index(needle) for needle in s])! Especially if your list is sorted.

NumPy, np.searchsorted :

import numpy as np

t = np.arange(0.5,10.5,0.5)
s = [3, 5, 7]

np.searchsorted(t, s)

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]
+5

Source: https://habr.com/ru/post/1668344/


All Articles