How exactly does a generator comprehension work?

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

    List/generator comprehension is a construct which you can use to create a new list/generator from an existing one.

    Let's say you want to generate the list of squares of each number from 1 to 10. You can do this in Python:

    >>> [x**2 for x in range(1,11)]
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    

    here, range(1,11) generates the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], but the range function is not a generator before Python 3.0, and therefore the construct I've used is a list comprehension.

    If I wanted to create a generator that does the same thing, I could do it like this:

    >>> (x**2 for x in xrange(1,11))
    <generator object at 0x7f0a79273488>
    

    In Python 3, however, range is a generator, so the outcome depends only on the syntax you use (square brackets or round brackets).

    0 讨论(0)
提交回复
热议问题