How exactly does a generator comprehension work?

前端 未结 7 681
清酒与你
清酒与你 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:48

    Generator comprehension is an easy way of creating generators with a certain structure. Lets say you want a generator that outputs one by one all the even numbers in your_list. If you create it by using the function style it would be like this:

    def allEvens( L ):
        for number in L:
            if number % 2 is 0:
                yield number
    
    evens = allEvens( yourList )
    

    You could achieve the same result with this generator comprehension expression:

    evens = ( number for number in your_list if number % 2 == 0 )
    

    In both cases, when you call next(evens) you get the next even number in your_list.

提交回复
热议问题