Skip to main content
 首页 » 编程设计

python之查找列表中元素的索引。二分查找还是使用索引函数

2025年05月04日15jackei

我是 python 的新手,一直在编写一个练习程序来根据 400 万个单词的列表检查密码。我原来的解决方案是这样的(如果密码包含在列表中,将打印 true):

import sys 
from bisect import bisect_left  
 
script, password, pwlist = sys.argv 
password = password+"\r\n" 
 
l=[line for line in open(pwlist)]  
l.sort() #Must be sorted for bisect_left to work                          
 
print (password <= l[-1]) and (l[bisect_left(l, password)] == password) 

然后我意识到我可以改用 index 方法,如下所示:

import sys 
 
script, password, pwlist = sys.argv 
password = password+"\r\n" 
 
l=[line for line in open(pwlist)] #Note we don't need to sort this time 
 
#Catch the "not in list" exception 
try: 
    print (password <= l[-1]) and (l[l.index(password)] == password) 
except ValueError: 
    print "False" 

我的第二个版本大大减少了执行时间,因为列表不需要排序。我以正确的方式处理这个问题吗? index() 方法如何工作?如果它适用于未排序的列表,那么它肯定不会进行二进制搜索。对此有任何建议,我们将不胜感激。

请您参考如下方法:

是的,在第一个示例中,您首先要自己设计一个算法,即二分搜索。

在第二个示例中,您只需使用 python 内置的 list.index() 函数。

第二种方法更快,因为排序列表的成本:O(N*log(N)) 比线性搜索的成本大数组:O(N)。

考虑一下:如果您必须检查多个密码,最好对排序列表进行一次排序和存储,然后在排序后的列表上使用二进制搜索。