您可能会考虑trie或DAWG或数据库。有几个相同的Python实现。
下面是一些相对定时为你考虑一组VS列表:
import timeit
import random
with open('/usr/share/dict/words','r') as di: # UNIX 250k unique word list
all_words_set={line.strip() for line in di}
all_words_list=list(all_words_set) # slightly faster if this list is sorted...
test_list=[random.choice(all_words_list) for i in range(10000)]
test_set=set(test_list)
def set_f():
count = 0
for word in test_set:
if word in all_words_set:
count+=1
return count
def list_f():
count = 0
for word in test_list:
if word in all_words_list:
count+=1
return count
def mix_f():
# use list for source, set for membership testing
count = 0
for word in test_list:
if word in all_words_set:
count+=1
return count
print "list:", timeit.Timer(list_f).timeit(1),"secs"
print "set:", timeit.Timer(set_f).timeit(1),"secs"
print "mixed:", timeit.Timer(mix_f).timeit(1),"secs"
打印:
list: 47.4126560688 secs
set: 0.00277495384216 secs
mixed: 0.00166988372803 secs
即匹配一组的10000个字与一组25万个字是17,085 X更快比匹配相同的250,000单词列表中相同的10000个单词列表。使用源代码列表和成员资格测试集合是28,392 X更快比单独未排序列表更快。
对于成员资格测试,列表是O(n),集合和字典是O(1)用于查找。
结论:为600万行文本使用更好的数据结构!
是否有任何理由不能使用一组单词来代替?可能有6亿行,但使用的英语单词少得多(如果不清除它,甚至包括前导和尾随标点符号)。测试集合中的成员应该非常快。 – DSM
@DSM:O(1)实际上,假设散列冲突相对较少:) –
您无法检查项目是否在列表中有效。这不是列表的目的。你需要选择你的数据类型(特别是集合),以适合你将要使用的数据类型,因为没有任何数据类型对每件事都很好。 – Ben