Python 从特定位置恢复(或启动)itertools.permutations?

Python 从特定位置恢复(或启动)itertools.permutations?,python,Python,假设我运行以下脚本 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 Keyb

假设我运行以下脚本

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的起始点?

如果不退出脚本,只需保留迭代器并在以后继续使用它即可。由于重新开始,迭代器将在从头开始的状态下创建<代码>迭代工具> />代码>在中间没有特殊的API,一般来说,发电机没有这个特性,因为它们具有在迭代时演化的内部状态。因此,在一个新的发电机中间启动的唯一方法是消耗一定数量的元素并将它们扔掉。没有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
你有两个选择:

  • 跳过您已经看到的排列(如您所建议的),或者
  • 编写自己的函数,该函数接受一个起点

如果以“wb”而不是“w”打开文件,Karoly Horvath的答案应该可以正常工作

在停止脚本之前,可以使用pickle将置换生成器存储在文件中。 恢复脚本时,从文件中将置换生成器读取为“rb”

输出:

working!

我不知道它是什么时候被引入的,但是在Python3.4中,一些迭代器可以被pickle,包括itertools产品、置换等。因此,我认为可以编写一些代码来实现这一点。
working!