我可以在python上暂停itertools,然后再继续吗?
我需要创建一个字符串列表,其中包含所有字母大写和小写的所有可能组合,以及长度为 14 的非重复字符,这很庞大,我知道这将花费大量的时间和空间。我现在的代码是这样的:
import itertools
filename = open("strings.txt", "w")
for com in itertools.permutations('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 14):
filename.write("n"+"1_"+"".join(com)+"n"+"0_"+"".join(com))
print ("".join(com))
非常基本,它可以完成工作,但我还没有找到更快的方法(尝试了一种我发现似乎更快但 python 更快的 java 算法)因为这将需要很长时间,我不时需要关闭我的电脑,所以我需要能够保存我离开的地方并继续,否则每次它崩溃/关闭我的电脑/发生任何事情时我都会从头开始。有没有办法做到这一点?
回答
您可以pickle使用迭代器对象。它的内部状态将存储在pickle文件中。当你恢复时,它应该从它停止的地方开始。
像这样的东西:
import itertools
import os
import pickle
import time
# if the iterator was saved, load it
if os.path.exists('saved_iter.pkl'):
with open('saved_iter.pkl', 'rb') as f:
iterator = pickle.load(f)
# otherwise recreate it
else:
iterator = itertools.permutations('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 14)
try:
for com in iterator:
# process the object from the iterator
print(com)
time.sleep(1.0)
except KeyboardInterrupt:
# if the script is about to exit, save the iterator state
with open('saved_iter.pkl', 'wb') as f:
pickle.dump(iterator, f)
结果是:
>python so_test.py
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n')
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'o')
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'p')
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'q')
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'r')
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 's')
>python so_test.py
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 't')
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'u')
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'v')
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'w')