繁体   English   中英

返回数字列表中第一个索引的最有效方法是什么,该索引与数字本身匹配?

[英]What is the most efficient method of returning the first index in a list of numbers whereby that index matches the number itself?

例子:

list1 = [1,4,2] ---> 将返回 2

list2 = [9, 5, 7, 4, 4] ---> 将返回 4

我目前的代码:

def my_function(list):
    for i in range(len(list)):
        if list[i] == i:
            return i
    return -1

如果没有匹配项,则返回 -1。 我正在寻找最快、性能最快的方法,因为我正在使用的列表可能很长。 我当前的代码有效,但我想知道最有效的方法。

使用enumerate而不是你的range(len(list))东西:

In [20]: def g(lst):
    ...:     for i, j in enumerate(lst):
    ...:         if i == j:
    ...:             return i
    ...:     return -1
    ...:     

In [21]: g(list1)
Out[21]: 2

In [22]: g(list2)
Out[22]: 4

In [23]: g([1,2,3,4])
Out[23]: -1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM