简体   繁体   中英

Function generators Python

I was trying to implement a function generator to be used n times. My idea was to create a generator object, then assign that object to another variable and call the re-assigned variable as the function, example:

def generator:
   [...]
   yield ...

for x in xrange(10):
   function = generator
   print function(50)

When I call the print function, I observe that function(50) was not called. Instead the output is: <generator object...> . I was trying to use this function 10 times by assigning it to a generator function, and using this new variable as the generator function.

How can I correct this?

Generator Functions return generator objects. You need to do list(gen) to convert them into a list or just iterate over them.

>>> def testFunc(num):
        for i in range(10, num):
            yield i


>>> testFunc(15)
<generator object testFunc at 0x02A18170>
>>> list(testFunc(15))
[10, 11, 12, 13, 14]
>>> for elem in testFunc(15):
        print elem


10
11
12
13
14

This question explains more about it: The Python yield keyword explained

You can also create generator objects with a generator expression:

>>> (i for i in range(10, 15))
<generator object <genexpr> at 0x0258AF80>
>>> list(i for i in range(10, 15))
[10, 11, 12, 13, 14]
>>> n, m = 10, 15
>>> print ('{}\n'*(m-n)).format(*(i for i in range(n, m)))
10
11
12
13
14

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM