简体   繁体   中英

how to use python generators

today im learning generators iterator and so on in other to save memory,i think rather then have the list dumped in memory its better to have them evaluated when needed so i make a simple test like below a generator like so.

def test(*args):
    for i in args:
        yield i

when i use it like below it give the desired effect.

for i in test(range(10)):
    print i

with output like so

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

but this then range will dump all the number in to the function which defeats the purpose so i tried xrange like below

for i in test(xrange(10)):
    print i

i get a rather surprising output like this

xrange(10)

but looking the other way since xrange will only be evaluate when iterated so i try forcing it to do it like so

for i in ye(*xrange(10)):
    print i

and then i got an output like this

o
1
.
.

can someone explain what is going on in details please

Using * in a function definition requires the caller to provide separate arguments to the function. Consider removing it and using args directly.

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