【发布时间】:2015-04-15 03:35:24
【问题描述】:
我打算根据每行中的键将一个总共约500MB的文件读入一个dict。代码sn-p如下:
f2 = open("ENST-NM-chr-name.txt", "r") # small amount
lines = [l.strip() for l in f2.readlines() if l.strip()]
sample = dict([(l.split("\t")[2].strip("\""), l) for l in lines]) ## convert [(1,2), (3,4)] to {1:2, 3:4}
在内存为 4GB 的机器上运行时,python 会报内存错误。如果我将sample 变量的求值表达式更改为[l for l in lines],它可以正常工作。
一开始,我以为是split方法消耗了很多内存,所以我把我的代码调整成这样:
def find_nth(haystack, needle, n):
start = haystack.find(needle)
while start >= 0 and n > 1:
start = haystack.find(needle, start+len(needle))
n -= 1
return start
...
sample = dict([(l[find_nth(l, "\t", 4):].strip(), l) for l in lines])
但结果是一样的。
一个新的发现是它可以在没有OOM的情况下正常运行,只要我删除dict()转换而不考虑代码逻辑。
谁能给我一些关于这个问题的想法?
【问题讨论】:
-
这个网站上的某个地方是关于
dict占用多少内存的问题,这比您预期的要多得多。 -
您能否给出与您提到的内容相关的具体网址链接?谢谢。 @MarkRansom
-
如果我能记住它,我早就这么做了。对不起。
-
另外,您是否在阅读制表符分隔值?
标签: python