How to loop through a generator

2019-03-09 06:26发布

问题:

How can one loop through a generator? I thought about this way:

gen = function_that_returns_a_generator(param1, param2)
if gen: # in case the generator is null
    while True:
        try:
            print gen.next()
        except StopIteration:
            break

Is there a more pythonic way?

回答1:

Simply

for x in gen:
    # whatever

will do the trick. Note that if gen always returns True.



回答2:

for item in function_that_returns_a_generator(param1, param2):
    print item

You don't need to worry about the test to see if there is anything being returned by your function as if there's nothing returned you won't enter the loop.



回答3:

In case you don't need the output of the generator because you care only about its side effects, you can use the following one-liner:

for _ in gen: pass


回答4:

Just treat it like any other iterable:

for val in function_that_returns_a_generator(p1, p2):
    print val

Note that if gen: will always be True, so it's a false test



回答5:

You can simply loop through it:

>>> gen = (i for i in range(1, 4))
>>> for i in gen: print i
1
2
3

But be aware, that you can only loop one time. Next time generator will be empty:

>>> for i in gen: print i
>>> 


回答6:

If you want to manually move through the generator (i.e., to work with each loop manually) then you could do something like this:

    from pdb import set_trace

    for x in gen:
        set_trace()
        #do whatever you want with x at the command prompt
        #use pdb commands to step through each loop of the generator e.g., >>c #continue