yield from grammar application

yield from python3.3 is new in grammar, syntax structure: yield from iterable

 

In the last article in a my_chain custom function, you can now yield from its streamlined method

 

# Customize a chain

DEF my_chain (* args, ** kwargs):
     "" " Note: args is a tuple, tuple is an iterable " "" 
    for iterable_obj in args:
         for value in iterable_obj:
             yield value

DEF my_chain02 (* args, ** kwargs):
     "" " Note: args is a tuple, tuple is an iterable " "" 
    for iterable_obj in args:
         yield  from iterable_obj   # line of code did two lines of code to do 
        # for in iterable_obj value: 
        #      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,

 

 

The difference between the yield and the yield from

DEF g1 (Iterable):
     "" " yield a direct return to the iterables " "" 
    yield Iterable


DEF G2 (Iterable):
     "" " the yield directly from each element returned iterator object " "" 
    the 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,

Guess you like

Origin www.cnblogs.com/z-qinfeng/p/12109821.html