yield from 是python3.3中新增的语法, 语法结构: yield from iterable
在上一篇文章中自定义了一个my_chain函数,现在可以yield from方法对其进行精简
# 自定义一个chain def my_chain(*args, **kwargs): """注意: args是一个tuple, tuple是一个可迭代对象""" for iterable_obj in args: for value in iterable_obj: yield value def my_chain02(*args, **kwargs): """注意: args是一个tuple, tuple是一个可迭代对象""" for iterable_obj in args: yield from iterable_obj # 一行代码干了两行代码的事 # for value in iterable_obj: # yield value for value in my_chain02(my_list, my_dict, range(20, 30)): print(value, end=",") # 1,2,3,name,age,20,21,22,23,24,25,26,27,28,29,
yield和yield from的区别
def g1(iterable): """yield直接返回这个可迭代对象""" yield iterable def g2(iterable): """yield from 直接返回迭代对象中的每个元素""" yield from iterable for value in g1(range(10)): print(value) # range(0, 10) for value in g2(range(10)): print(value, end=',') # 0,1,2,3,4,5,6,7,8,9,
日拱一卒无有尽,功不唐捐终入海