【发布时间】:2016-03-01 15:19:04
【问题描述】:
我有单词“somewhat”或“qqqw”,想在英语单词列表中找到它(它存在与否,在列表中)。
如果我有list of str,那么
is_exists = s in english_list
如果我们有大量的单词列表,这种方法会很慢。我认为需要某种数据结构或算法来使其更快更高效
那我该怎么做,有什么建议吗?
【问题讨论】:
我有单词“somewhat”或“qqqw”,想在英语单词列表中找到它(它存在与否,在列表中)。
如果我有list of str,那么
is_exists = s in english_list
如果我们有大量的单词列表,这种方法会很慢。我认为需要某种数据结构或算法来使其更快更高效
那我该怎么做,有什么建议吗?
【问题讨论】:
这里有一些很好的比较: https://wiki.python.org/moin/TimeComplexity
你需要的可能是一套。
【讨论】:
正如建议的那样,创建set 而不是list 会更快。
对于“小”数据文件,list 似乎更快,但一旦文件变大,访问set 就会比列表更快。
用这样的东西测试它:
from timeit import default_timer as timer
import sys
try:
lookfor = sys.argv[1]
pass
except:
print "Program requires an word to look for"
sys.exit()
wordset = set()
wordlist = []
with open("your file name","r") as f:
for i in f.readlines():
wordset.update(i.split())
for x in i.split():
wordlist.append(x)
def testwords(word):
start= timer()
if word in wordset: print ("Yes word found")
else: print ("No word not found")
end= timer()
print ("Wordset",str(len(wordset)))
print (start,end,(end - start)*1000)
start= timer()
if word in wordlist: print ("Yes word found")
else: print ("No word not found")
end= timer()
print ("Wordlist",str(len(wordset)))
print (start,end,(end - start)*1000)
testwords(lookfor)
【讨论】:
我在其他主题中找到了答案。对不起,我没有先找到它。
我需要使用bisect 模块和函数bisect_left。它可以快速找到列表中的项目,排序列表。
它在庞大的列表中速度很快。
【讨论】: