我有一个排序的数字列表,比如:
a = [77,98,99,100,101,102,198,199,200,200,278,299,300,300,300]
我需要找到每个值的最大索引,它可以被100整除。
输出应为:
4,10,15
My Code:
a = [77,98,99,100,101,102,198,199,200,200,278,299,300,300,300]
idx = 1
for i in (a):
if i%100 == 0:
print idx
idx = idx+1
以上代码输出:
4
9
10
13
14
15
最佳答案
为了防止人们好奇,我将dict理解技术与反向迭代技术进行了对比。听写理解的速度是原来的两倍。更改为OrderedDict
导致大幅度减速。大约比听写慢15倍。
def test1():
a = [77,98,99,100,101,102,198,199,200,200,278,299,300,300,300]
max_index = {}
for i, item in enumerate(a[::-1]):
if item not in max_index:
max_index[item] = len(a) - (i + 1)
return max_index
def test2():
a = [77,98,99,100,101,102,198,199,200,200,278,299,300,300,300]
return {item: index for index, item in enumerate(a, 1)}
def test3():
a = [77,98,99,100,101,102,198,199,200,200,278,299,300,300,300]
OrderedDict((item, index) for index, item in enumerate(a, 1))
if __name__ == "__main__":
import timeit
print(timeit.timeit("test1()", setup="from __main__ import test1"))
print(timeit.timeit("test2()", setup="from __main__ import test2"))
print(timeit.timeit("test3()", setup="from __main__ import test3; from collections import OrderedDict"))
3.40622282028
1.97545695305
26.347012043
关于python - Python列表中被“n”整除的重复元素的最大索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45597956/