Pete Lavelle
Pete Lavelle

Reputation: 103

How do I return the index number for nth occurrence of a given value?

Keeping the question as generic as possible - I have a list of values and need to return the index of the nth occurrence of a specified value...

list = [0,0,1,1,0,1,0,0,0,1,0,1,1,0,1,0]
occurrence = 5
value = 1

So I am looking for the index of the 5th time that the value 1 occurs. In the example above, the returned value should be 11.

'occurrence' and 'value' are variables that need to be set by the user

EDIT

Thanks for the help guys, been playing around with various options and came up with this one

valList = [0,0,1,1,0,1,0,0,0,1,0,1,1,0,1,0]
occurrence = 5
value = 1

count = 0
rowIndex = -1

for val in valList:
    if count < occurrence:
        rowIndex += 1
        if val == valCR:
            count += 1

Upvotes: 0

Views: 256

Answers (2)

georg
georg

Reputation: 215039

Here's an efficient version:

def nth_index(sequence, n, value):
    i = -1
    for _ in xrange(n):
        i = sequence.index(value, i + 1)
    return i

 lst = [0,0,1,1,0,1,0,0,0,1,0,1,1,0,1,0]
 print nth_index(lst, 5, 1) # 11

This behaves like the built-in index and raises a ValueError when the value is not found or n is too large:

 print nth_index(lst, 55, 1) # ValueError: 1 is not in list

FTR, timings:

import timeit, itertools

lst = range(1000) * 5
value = 0
occurrence = 5

print timeit.timeit(lambda: [i for i,elem in enumerate(lst) if elem==value][occurrence-1], number=1000)
print timeit.timeit(lambda: next(itertools.islice((i for i,elem in enumerate(lst) if elem==value), occurrence-1, occurrence)), number=1000)
print timeit.timeit(lambda: nth_index(lst, occurrence, value), number=1000)

--

0.52188706398
0.416564941406
0.117225885391

Upvotes: 2

inspectorG4dget
inspectorG4dget

Reputation: 114035

>>> mylist = [0,0,1,1,0,1,0,0,0,1,0,1,1,0,1,0]
>>> occurrence = 5
>>> value = 1
>>> [i for i,elem in enumerate(mylist) if elem==value][occurrence-1]
11

Or, the itertools way:

>>> next(itertools.islice((i for i,elem in enumerate(mylist) if elem==value), occurrence-1, occurrence))
11

Upvotes: 3

Related Questions