V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
fanqieipnet
V2EX  ›  推广

如何使用 enumerate 装饰?

  •  
  •   fanqieipnet · 2021-01-11 17:54:55 +08:00 · 502 次点击
    这是一个创建于 1207 天前的主题,其中的信息可能已经有所发展或是发生改变。
    如何使用 enumerate 装饰?今天番茄加速就来讲一下。

       enumerate 装饰

       for i, it in enumerate(iterators):

      ...

       iterators[i] = repeat(fillvalue)

       enumerate 装饰后会得到一个由 index 和元素本身组成的 tuple,举个例子:

       In [1]: for i,ele in enumerate([9,4,2,5,8]):

      ...: print((i,ele))

      ...:

      (0, 9)

      (1, 4)

      (2, 2)

      (3, 5)

      (4, 8)

      此处使用 enumerate,因后面先遍历完的 iter(a),为保证和 iter(b)个数对齐,需要填充 fillvalue 值,需要知道 a 的 index,此处为 0.

      捕获迭代终止异常

       try:

       value = next(it)

       except StopIteration:

      ...

       try… except 是异常捕获的标准模板,next(it)第一次执行返回 it 的第一个元素,a=[1,2,3],所以 value 值为 1.

      计数

       num_active 表示当前存活的列表个数,一旦一个列表迭代到终点,num_active 立即减 1

       num_active -= 1

       repeat

       iterators[i] = repeat(fillvalue)

       repeat 是 itertools 模块内另一个函数,如果 times 为默认值,则表示重复无限次,此处是一个 repeat 的典型用法。此处稍加注意,不要以为 times 参数默认值为 1,或者不理解为什么要无限次重复,记住这种用法。

      此处,repeat 返回一个无限次重复 fillvalue 值的迭代器,并赋值给此时触发 StopIteration 异常的列表。此处就是 iter(a),令其指向 repeat 创建的迭代器。

       yield 返回值

       value = fillvalue

       values.append(value)

       yield tuple(values)

      第一句,是在触发 StopIteration 时,将默认值 fillvalue 赋给 value,values 保存住列表对齐后位置的元素,第一次 for 退出时,values 内值为[1,4]
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2173 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:03 · PVG 19:03 · LAX 04:03 · JFK 07:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.