python中的yield

使用方式

def counter():
  print('counter start...')
  for i in range():
    a = yield i
    print(f'a is {a}')

counter()
# <generator object counter at 0x000001E7DA8B09E0>

counter()
# <generator object counter at 0x000001E7DA8B09E1>

f = counter()
print(next(f))
#  counter start...
#  0

print(next(f))
# a is None
# 1

print(next(f))
# a is None
# 2

yield关键字可以看作是return,代码执行到这里就会停止执行并返回其后面的值。下次调用的时候就会接着其后面继续执行

使用yield返回值的方法 **每次** 调用时会产生一个迭代器对象,如上述代码中 counter() 生成一个 generator object,将该迭代器赋值给一个变量(上述代码中的 f ),就可以对该变量使用迭代操作了。

自动计数器

记录步数的时候好用,例如使用tensorboard追踪神经网络参数时需要填写一个step参数

方法一:

import itertools

c = itertools.count()

next(c)  # 0
next(c)  # 1
next(c)  # 2

方法二(使用yield,有点脱裤子放屁):

def counter():
  i = 0
  while True:
    yield i
    i += 1

c = counter()

next(c)  # 0
next(c)  # 1
next(c)  # 2

Leave a Comment