我有Python代码,可以让我迭代组合列表,我想跳过迭代并生成例如每100次迭代。我有一个 next() 函数,可以让组合暂时迭代 1,但我需要跳过它们。
我现在拥有的代码是:
def fastFunction(string, string1):
try:
return next(string)
except StopIteration:
return None
这个函数可以让我在迭代器被调用时生成下一个迭代。
class MyIterator:
def __init__(self, hex_string, repeat, mapping_function=None, fixed_string=""):
self.fixed_string = fixed_string # Add a parameter for the fixed string
combined_string = fixed_string+hex_string
self.repeat = repeat
self.mapping_function = mapping_function
if self.mapping_function:
combined_string = self.mapping_function(combined_string)
self.hex_string = combined_string
self.fixed_part_length = len(fixed_string)
self.combinations = itertools.product(self.hex_string, repeat=repeat - self.fixed_part_length)
self.current = fastFunction(self.combinations, None)
def __iter__(self):
return self
def modify_speed(self):
pass
def __next__(self):
if self.current is not None:
private_key = self.fixed_string+ ''.join(self.current) # Ensure the fixed string is part of the final key
self.current = fastFunction(self.combinations, None)
return private_key
else:
raise StopIteration
这就是迭代器,函数传入 self.current 等东西,让下一个组合出现。我想跳过迭代,这样我就可以立即生成每 100 次迭代。我怎样才能做到这一点?
要修改 MyIterator 类以跳过迭代并每 100 次迭代生成一次,您可以增强 fastFunction 以将迭代器推进指定的步数。
这是您的代码,稍作修改,进行了以下更改:
import itertools
def fastFunction(iterator, skip):
try:
for _ in range(skip + 1):
next_value = next(iterator)
return next_value
except StopIteration:
return None
class MyIterator:
def __init__(self, hex_string, repeat, mapping_function=None, fixed_string="", skip=0):
self.fixed_string = fixed_string # Add a parameter for the fixed string
combined_string = fixed_string + hex_string
self.repeat = repeat
self.mapping_function = mapping_function
if self.mapping_function:
combined_string = self.mapping_function(combined_string)
self.hex_string = combined_string
self.fixed_part_length = len(fixed_string)
self.combinations = itertools.product(self.hex_string, repeat=repeat - self.fixed_part_length)
self.skip = skip
self.current = fastFunction(self.combinations, self.skip)
def __iter__(self):
return self
def modify_speed(self, new_skip):
self.skip = new_skip
def __next__(self):
if self.current is not None:
private_key = self.fixed_string + ''.join(self.current) # Ensure the fixed string is part of the final key
self.current = fastFunction(self.combinations, self.skip)
return private_key
else:
raise StopIteration
# Example usage
iterator = MyIterator("0123456789ABCDEF", 4, fixed_string="fixed", skip=99) # Skip 99 iterations to get every 100th
for _ in range(10): # Get first 10 elements
print(next(iterator))