Using return (list) vs yield

99封情书 提交于 2020-01-03 05:18:32

问题


I've created two enumeration methods, one which returns a list and the other which returns a yield/generator:

def enum_list(sequence, start=0):
    lst = []
    num = start
    for sequence_item in sequence:
        lst.append((num, sequence_item))
        num += 1
    return lst


def enum_generator(sequence, start=0):
    num = start
    for sequence_item in sequence:
        yield (num, sequence_item)
        num += 1

A few questions on this:

(1) Is changing a list to a generator as simple as doing:

# build via list
l = list()
for item in items:
    l.append(item)

# build via iterator
# l = list() (1) <== delete this line
for item in items:
    yield item # (2) change l.append(...) to yield ...

(2) Is "lazy evaluation" the only reason to use a generator, or are there other reasons as well?


回答1:


(1) generator are simply created as adding yield to your iteration.

(2) Yes, for lazy evaluation. But generators are also used to create stack and queue as they can be only iterate once. This property is also exploited in context manager, by yielding the context.




回答2:


An additional difference in your case is that since list is created before use and generator is evaluated at each next call, the generator function can check the context and come to different result for each yield, depending on external conditions, which vary with time.

Consider pseudocode:

def alloted_time():
    while True:
         if len(global_queue)>10:
            yield 5
         else:
            yield 10

If queue is large, allot 5 mins for next person, else 10.



来源:https://stackoverflow.com/questions/58494900/using-return-list-vs-yield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!