首页 > 解决方案 > python产品迭代链内存不足

问题描述

我正在尝试构建一个可能的字符串组合列表,然后对其进行迭代。我在执行以下行时内存不足,因为它有数十亿行。

data = list(map(''.join,chain.from_iterable(product(string.digits+string.ascii_lowercase+'/',repeat = i) for i in range(0,7))))

所以我认为,我不是创建这个庞大的可迭代列表,而是创建它并使用某种“保存字符串”在波中执行它,我将其保存到内存中,并且可以在我想要的时候重新启动。IE,生成并迭代一百万行,然后将保存字符串保存到文件中。然后从接下来的一百万行重新开始,但在“保存字符串”或下一行开始我的映射/迭代。我不知道该怎么做。我想我可能不必使用.from_iterable(product(我已经实现的代码。如果这个想法不清楚(或清楚但愚蠢),请告诉我。

此外,另一种选择不是解决内存问题,而是以某种方式优化可迭代列表本身,我也不确定我会如何做到这一点。我正在尝试映射一个没有现有文档的 API。虽然我不知道要采用非详尽的清单,但我当然愿意接受建议。

这是我一直在使用的代码块:

import csv
import string
from itertools import product, chain

#Open stringfile. If it doesn't exist, create it
try:
     with open(stringfile) as f:
     reader = csv.reader(f,delimiter=',')
     data = list(reader)
     f.close()
except:
     data = list(map(''.join, chain.from_iterable(product(string.digits+string.ascii_lowercase + '/', repeat = i) for i in range(0,6))))
     f=open(stringfile,'w')
     f.write(str('\n.join(data)))
     f.close()
     pass

#Iterate against
...

编辑:进一步戳这个让我找到了这个主题,这是一个类似的话题。有关于使用 islice 的讨论,这有助于我进行后期映射(由于我的异常处理错误,脚本昨晚在执行 API 调用时崩溃了)。我刚刚在第 400k 次迭代时重新启动它。

我可以在产品中使用 .islice 吗?那么对于生成器,生成 10mil-12mil 的项目(例如)并仅对这些项目进行操作以保留内存?

这是我正在做的最新片段。您可以看到我在实际迭代中进一步插入了 islice,但我想在实际生成(data =行)中进行 islice。

#Open stringfile. If it doesn't exist, create it
try:
    with open(stringfile) as f:
        reader = csv.reader(f,delimiter=',')
        data = list(reader)
    f.close()
except:
    data = list(map(''.join, chain.from_iterable(product(string.digits + string.ascii_lowercase + '/',repeat = i) for i in range(3,5))))
    f=open(stringfile,'w')
    f.write(str('\n'.join(data)))
    f.close()
    pass

print("Total items: " + str(len(data)-substart))
fdf = pd.DataFrame()
sdf = pd.DataFrame()
qdf = pd.DataFrame()
attctr = 0
#Iterate through the string combination list
for idx,kw in islice(enumerate(data),substart,substop):
    #Attempt API call. Do the cooldown function if there is an issue.
    if idx/1000 == int(idx/1000):
        print("Iteration " + str(idx) + " of " + str(len(data)))
    attctr +=1
    if attctr == attcd:
        print("Cooling down!")
        time.sleep(cdtimer)
        attctr = 0
    try:
....

标签: pythonloopspython-requestsout-of-memory

解决方案


推荐阅读