Understanding generators in Python

前端 未结 12 1836
日久生厌
日久生厌 2020-11-21 05:46

I am reading the Python cookbook at the moment and am currently looking at generators. I\'m finding it hard to get my head round.

As I come from a Java background, i

12条回答
  •  庸人自扰
    2020-11-21 06:22

    Experience with list comprehensions has shown their widespread utility throughout Python. However, many of the use cases do not need to have a full list created in memory. Instead, they only need to iterate over the elements one at a time.

    For instance, the following summation code will build a full list of squares in memory, iterate over those values, and, when the reference is no longer needed, delete the list:

    sum([x*x for x in range(10)])

    Memory is conserved by using a generator expression instead:

    sum(x*x for x in range(10))

    Similar benefits are conferred on constructors for container objects:

    s = Set(word  for line in page  for word in line.split())
    d = dict( (k, func(k)) for k in keylist)
    

    Generator expressions are especially useful with functions like sum(), min(), and max() that reduce an iterable input to a single value:

    max(len(line)  for line in file  if line.strip())
    

    more

提交回复
热议问题