保持问题尽可能通用 - 我有一个值列表,需要返回指定值的第n次出现的索引...
list = [0,0,1,1,0,1,0,0,0,1,0,1,1,0,1,0]
occurrence = 5
value = 1
所以我正在寻找值1发生的第5次索引。在上面的示例中,返回的值应为11。
'occurrence'和'值'是需要由用户设置的变量
感谢帮助人员,一直在玩各种选项,想出了这个
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
答案 0 :(得分:3)
>>> 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
或者,itertools
方式:
>>> next(itertools.islice((i for i,elem in enumerate(mylist) if elem==value), occurrence-1, occurrence))
11
答案 1 :(得分:2)
这是一个有效的版本:
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
此行为类似于内置index
,并在找不到值或n
太大时引发ValueError:
print nth_index(lst, 55, 1) # ValueError: 1 is not in list
FTR,时间:
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