gpt4 book ai didi

python - 我可以在 python 上暂停 itertools,然后再继续吗?

转载 作者:行者123 更新时间:2023-12-03 23:58:04 25 4
gpt4 key购买 nike

我需要创建一个字符串列表,其中包含所有字母大写和小写的所有可能组合,非重复字符,长度为 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')

关于python - 我可以在 python 上暂停 itertools,然后再继续吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67764274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com