[英]What's the fastest way to save/load a large collection (list/set) of strings in Python 3.6?
该文件的长度为5gb。
我确实在stackoverflow上找到了一个类似的问题,人们建议使用numpy数组,但是我想这种解决方案将适用于数字而不是字符串的集合。
是否有任何东西可以击败eval(list.txt)或导入一个变量设置为列表的python文件?
加载/保存python字符串列表的最有效方法是什么?
对于只读情况:
import numpy as np
class IndexedBlob:
def __init__(self, filename):
index_filename = filename + '.index'
blob = np.memmap(filename, mode='r')
try:
# if there is an existing index
indices = np.memmap(index_filename, dtype='>i8', mode='r')
except FileNotFoundError:
# else, create it
indices, = np.where(blob == ord('\n'))
# force dtype to predictable file
indices = np.array(indices, dtype='>i8')
with open(index_filename, 'wb') as f:
# add a virtual newline
np.array(-1, dtype='>i8').tofile(f)
indices.tofile(f)
# then reopen it as a file to reduce memory
# (and also pick up that -1 we added)
indices = np.memmap(index_filename, dtype='>i8', mode='r')
self.blob = blob
self.indices = indices
def __getitem__(self, line):
assert line >= 0
lo = self.indices[line] + 1
hi = self.indices[line + 1]
return self.blob[lo:hi].tobytes().decode()
一些附加说明:
mmap
,如果你想看到它现有IndexedBlob
对象。 您可以避免这种情况,只需保留“松散”对象的列表即可。 n
个换行记录一次,然后在查找时间进行线性搜索来显着缩小索引的大小。 我发现这不值得。 '\\0'
而不是'\\n
作为分隔符。 而且当然:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.