You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python迭代器中实现步进跳过,获取指定间隔的迭代结果?

修改迭代器实现按步长跳过迭代项

核心思路

要实现每第100个迭代结果返回一个,本质是给迭代器添加步长控制:每次返回当前项后,跳过指定数量的中间项,直接取下一个目标项。以下是具体修改方案:

修改后的完整代码

import itertools

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="", step=1):
        self.fixed_string = fixed_string
        combined_string = fixed_string + hex_string
        self.repeat = repeat
        self.mapping_function = mapping_function
        self.step = max(1, step)  # 确保步长不小于1,避免无效输入
        
        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, new_step):
        # 动态调整步长,保证输入有效
        self.step = max(1, new_step)

    def _skip(self, count):
        # 辅助方法:跳过指定数量的元素,返回是否完成全部跳过
        for _ in range(count):
            try:
                next(self.combinations)
            except StopIteration:
                return False
        return True

    def __next__(self):
        if self.current is not None:
            private_key = self.fixed_string + ''.join(self.current)
            
            # 处理步长逻辑:跳过step-1个中间项
            if self.step > 1:
                skip_success = self._skip(self.step - 1)
                if skip_success:
                    # 跳过成功,取下一个目标项
                    self.current = fastFunction(self.combinations, None)
                else:
                    # 迭代器已耗尽,标记无后续项
                    self.current = None
            else:
                # 步长为1时,保留原有逻辑
                self.current = fastFunction(self.combinations, None)
            
            return private_key
        else:
            raise StopIteration

关键修改说明

  1. 新增步长参数
    在__init__中添加step参数(默认值为1,兼容原有逻辑),用max(1, step)确保步长不会小于1,避免无效输入。

  2. 新增_skip辅助方法
    专门负责跳过指定数量的元素,内部循环调用next(),如果中途遇到StopIteration则返回False,表示无法完成全部跳过操作。

  3. 修改__next__逻辑

    • 保留原有返回当前项的逻辑;
    • 当步长大于1时,先调用_skip跳过step-1个中间项;
    • 根据跳过结果更新current:跳过成功则取下一个目标项,失败则标记current为None,下次调用时触发迭代结束。
  4. 完善modify_speed方法
    让它可以动态调整步长,同样保证新步长不小于1,支持运行时修改跳过频率。

使用示例

# 创建步长为100的迭代器,每100个组合返回一个
my_iter = MyIterator(hex_string="0123456789abcdef", repeat=4, step=100)

for key in my_iter:
    print(key)
    # 可中途动态调整步长
    # my_iter.modify_speed(200)

内容的提问来源于stack exchange,提问作者Charles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 13:17:39