How exactly does a generator comprehension work?

前端 未结 7 852
清酒与你
清酒与你 2020-11-22 15:04

What does generator comprehension do? How does it work? I couldn\'t find a tutorial about it.

7条回答
  •  天命终不由人
    2020-11-22 15:52

    Generators are same as lists only, the minor difference is that in lists we get all the required numbers or items of the list at ones, but in generators the required numbers are yielded one at a time. So for getting the required items we have to use the for loop to get all the required items.

    #to get all the even numbers in given range
     
    def allevens(n):
        for x in range(2,n):
            if x%2==0:
                yield x
    
    for x in allevens(10)
    print(x)
    
    #output
    2
    4
    6
    8
    

提交回复
热议问题