我有一個包含5000萬行的384MB文本文件。每行包含2個空格分隔的整數:一個鍵和一個值。該文件按鍵排序。我需要一種有效的方式來查找Python中約200個鍵的列表的值。在Python中閱讀巨大文件
我目前的做法包括在下面。它需要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
我很樂意看到您的最終解決方案,因爲您似乎將它放在一起,但沒有提供代碼的答案。 – 2009-04-13 16:47:15
在問題結束時添加 – marcog 2009-04-13 17:01:35