Python学习: generator

关于 python 里的 generator 特性学习
更新于: 2022-08-18 12:32:34

示例

  • yield:每次执行到这里会将值返回出去
def g():
    yield 1
    yield 2
    yield 3

gen = g()

print(type(gen))  # 👉️ <class 'generator'>

# ⛔️ TypeError: object of type 'generator' has no len()
print(len(gen))

转化为list

generator 很小的时候,转化为 list,方便 debug

但如果较大的时候,这样操作就应该注意啦。

def g():
    yield 1
    yield 2
    yield 3


# 👇️ convert to list
my_list = list(g())

print(my_list)  # 👉️ [1, 2, 3]
print(len(my_list))  # 👉️ 

Note that once the generator is converted to a list, it is exhausted.

如果转为 list,这个 generator 将会被释放

def g():
    yield 1
    yield 2
    yield 3


# 👇️ convert to list
gen = g()

print(list(gen))  # 👉️ [1, 2, 3]
print(list(gen))  # 👉️ []

遍历

def g():
    yield 1
    yield 2
    yield 3


gen = g()

for i in gen:
    print(i)  # 👉️ 1, 2, 3

单次访问

可能用在 debug,每次访问的值的情况下,直接使用 next 来进行。

def g():
    yield 1
    yield 2
    yield 3


gen = g()

print(next(gen))  # 👉️ 1
print(next(gen))  # 👉️ 2
print(next(gen))  # 👉️ 3

类型

  • type 方法
  • isinstance 方法
import types


def g():
    yield 1
    yield 2
    yield 3


# 👇️ convert to list
gen = g()

print(type(gen)) # 👉️ <class 'generator'>

# 👇️ True
print(isinstance(gen, types.GeneratorType))

参考