假设我运行以下脚本
try:
while 1:
# Iteration processess of possibel keys
for length in range(7,8): # only do length of 7
for attempt in itertools.permutations(chars, length):
print(''.join(attempt))
except KeyboardInterrupt:
print "Keybord interrupt, exiting gracefully anyway."
sys.exit()它将开始打印
ABCDEFG
ABCDEFH
ABCDEFI
ABCDEFJ
etc..但是假设我退出/关闭脚本,迭代在ABCDEFJ处停止。
是否可以从该位置(ABCDEFJ)开始,这样我就不必遍历之前迭代过的位置(ABCDEFG, ABCDEFH, ABCDEFI)
问题:
如何选择itertools.permutations的起点
发布于 2016-02-24 22:58:18
如果不退出脚本,可以简单地保留迭代器,并在以后继续使用它。由于重新开始,迭代器将在从头开始的状态下创建。itertools.permutations没有专门的中间启动接口,生成器通常也没有这个特性,因为它们的内部状态会在迭代过程中发生变化。因此,在新的生成器中间开始的唯一方法是使用给定数量的元素并丢弃它们。
发布于 2016-02-24 23:02:06
你不能。没有API支持它,并且你不能序列化这些对象:
i=itertools.permutations('ABC', 2)
next(i) # ('A', 'B')
next(i) # ('A', 'C')
import pickle
with open('mypickle', 'w') as f:
pickle.dump(i, f)
...
File "/usr/lib/python2.6/copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle permutations objects您有两个选择:
发布于 2020-03-02 02:29:37
如果您以"wb“而不是"w”打开文件,那么Karoly Horvath的答案应该可以很好地工作。
在停止脚本之前,可以使用pickle将置换生成器存储在文件中。当您恢复脚本时,将文件中的置换生成器读取为"rb“。
from itertools import permutations
import pickle
string = "abcdefg"
to_file = permutations(string, 3)
next(to_file)
next(to_file)
with open('pickle.pickle', 'wb') as file:
pickle.dump(to_file, file)
with open("pickle.pickle", 'rb') as file:
from_file = pickle.load(file)
if next(from_file) == next(to_file):
print("working!")输出:
working!https://stackoverflow.com/questions/35605368
复制相似问题