我有这段代码,它会生成一致的字符串列表。
import itertools
choices = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"
for length in range(0,20):
for entry in itertools.product(choices, repeat = length):
string = ''.join(entry)
print string
我希望能够从上一个已知字符串继续运行此脚本。这怎么可能呢?
答案 0 :(得分:4)
import itertools
def choices():
choices = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"
for length in range(0,20):
for entry in itertools.product(choices, repeat = length):
string = ''.join(entry)
yield string
choice_seq = choices()
print next(choice_seq)
print next(choice_seq)
发电机的关键在于它们带着它们的状态。
答案 1 :(得分:2)
假设您将变量string
设置为最后一个已知字符串(或者在开始时开始''
):
import itertools
choices = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"
for length in range(len(string), 20):
itr = itertools.product(choices, repeat = length)
if string != '' and length == len(string):
itr = itertools.dropwhile(tuple(string).__ne__, itr)
for entry in itr:
string = ''.join(entry)
print string
请注意,这将打印的第一个元素是最后一个已知的字符串。如果你想跳过最后一个已知的并开始打印下一个字符串,你可以在if语句中做next(itr)
。
这假定您尝试在多次执行脚本或其他不适用生成器解决方案的情况下从中断处继续。如果你可以使用发电机,你应该。
答案 2 :(得分:0)
您的“已保存状态”只是当前长度和itertools.product
的当前状态。这两件事都可以腌制。所以,这里有一些伪代码:
import itertools
import pickle
choices = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"
def tryWithStateSave(currentlength, currentproduct):
try:
for entry in currentproduct:
string = ''.join(entry)
print string
except KeyboardInterrupt:
pickle.dump((currentlength, currentproduct), <saved state file>)
raise
if <a saved state file exists>:
currentlength, currentproduct = pickle.load(<the saved state file>)
tryWithStateSave(currentlength, currentproduct)
currentlength += 1
else:
currentlength = 0
for length in range(currentlength+1,20):
tryWithStateSave(length, itertools.product(choices, repeat = length))