我的第一个直觉是制作一个以名称为键的字典,假设使用字典中键的哈希查找名称是最有效的。
给定答案,@rfw 使用 a of names,我编辑了如下代码,并使用 a of names 和 aset
对这两种方法进行了测试。dict
set
我构建了一个包含超过 40 M 条记录和超过 5400 个名称的虚拟数据集。使用这个数据集,set 方法在我的机器上始终具有优势。
import re
from collections import Counter
import time
# names file downloaded from http://www.tucows.com/preview/520007
# the set contains over 5400 names
f = open('./names.txt', 'r')
names = [ name.rstrip() for name in f.read().split(',') ]
name_set = set(names) # set of unique names
names_dict = Counter(names) # Counter ~= dict of names with counts
# Expect: 246 lalala name="Jack";surname="Smith"
pattern = re.compile(r'.*\sname="([^"]*)"')
def select_rows_set():
f = open('./data.txt', 'r')
out_f = open('./data_out_set.txt', 'a')
for record in f.readlines():
name = pattern.match(record).groups()[0]
if name in name_set:
out_f.write(record)
out_f.close()
f.close()
def select_rows_dict():
f = open('./data.txt', 'r')
out_f = open('./data_out_dict.txt', 'a')
for record in f.readlines():
name = pattern.match(record).groups()[0]
if name in names_dict:
out_f.write(record)
out_f.close()
f.close()
if __name__ == '__main__':
# One round to time the use of name_set
t0 = time.time()
select_rows_set()
t1 = time.time()
time_for_set = t1-t0
print 'Total set: ', time_for_set
# One round to time the use of names_dict
t0 = time.time()
select_rows_dict()
t1 = time.time()
time_for_dict = t1-t0
print 'Total dict: ', time_for_dict
我假设 a 本质Counter
上是一个字典,并且更容易从数据集构建,不会增加访问时间的任何开销。如果我遗漏了什么,很高兴得到纠正。