5000 万行の 384MB のテキスト ファイルがあります。各行には、スペースで区切られた 2 つの整数 (キーと値) が含まれます。ファイルはキーでソートされます。Python で約 200 個のキーのリストの値を効率的に検索する方法が必要です。
私の現在のアプローチは以下に含まれています。30秒かかります。これをせいぜい数秒という合理的な効率に抑えるには、より効率的な Python foo が必要です。
# list contains a sorted list of the keys we need to lookup
# there is a sentinel at the end of list to simplify the code
# we use pointer to iterate through the list of keys
for line in fin:
line = map(int, line.split())
while line[0] == list[pointer].key:
list[pointer].value = line[1]
pointer += 1
while line[0] > list[pointer].key:
pointer += 1
if pointer >= len(list) - 1:
break # end of list; -1 is due to sentinel
コード化された二分探索 + シーク ソリューション (ありがとう kigurai!):
entries = 24935502 # number of entries
width = 18 # fixed width of an entry in the file padded with spaces
# at the end of each line
for i, search in enumerate(list): # list contains the list of search keys
left, right = 0, entries-1
key = None
while key != search and left <= right:
mid = (left + right) / 2
fin.seek(mid * width)
key, value = map(int, fin.readline().split())
if search > key:
left = mid + 1
else:
right = mid - 1
if key != search:
value = None # for when search key is not found
search.result = value # store the result of the search