我试图建立一个可能的字符串组合列表,然后对其进行迭代。我执行下面这行时内存不足,因为它有几十亿行。
data = list(map(''.join,chain.from_iterable(product(string.digits+string.ascii_lowercase+'/',repeat = i) for i in range(0,7))))
所以我认为,我没有创建这个庞大的iterable列表,而是创建它,并用某种“保持字符串”在波浪中对其执行,我将其保存到内存中,并可以在需要时重新启动。即,生成并迭代一百万行,然后将保留字符串保存到文件中。然后再开始下一个百万行,但从“保持字符串”或下一行开始映射/迭代。我不知道该怎么做。我想我可能得不使用
.from_iterable(product(
我已经实现的代码。如果这个想法不清晰(或者清晰但愚蠢),请告诉我。
另外,另一个选择不是解决内存问题,而是以某种方式优化iterable列表本身,我也不知道该怎么做。我正在尝试映射一个没有现有文档的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调用时脚本崩溃)。我刚在第40万台重新启动。
我能用吗。产品中的islice?那么,对于生成器,生成10mil-12mil(例如)项,并仅对这些项进行操作,以保留内存?
以下是我正在做的事情的最新片段。你可以看到,我在实际的迭代中进一步插入了islice,但我想在实际的生成中插入islice
data =
线路)。
#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:
....