简体   繁体   中英

Using yield in Python?

I have this code:

def generator(n):
    list_of = range(1,n+1)
    for i in list_of:
        if i % 7 == 0:
            yield i

print generator(100)

This should print all the numbers in the given range that are divisible by 7 , but the output is <generator object generator at 0x1004ad280> instead.

Also, the word yield in my text editor (KOD) doesn't appear highlighted in sky blue color like all the reserved words but instead appears in white, is that fine?

Your generator works . You forgot to iterate over it though:

for elem in generator(100):
    print elem

or you could turn it into a list:

print list(generator(100))

You instead printed the generator object produced by calling the generator function. A generator function produces a suspended generator. Only when you iterate over it is code executed (until the next yield ).

Demo:

>>> def generator(n):
...     list_of = range(1,n+1)
...     for i in list_of:
...         if i % 7 == 0:
...             yield i
... 
>>> print list(generator(100))
[7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98]

The list() call iterates over the given argument, producing a Python list object with all elements yielded by the argument. Great for iterating over a generator to pull in all the elements that it produces.

As for KOD; that editor hasn't seen updates in years now; you may want to switch to something else. As the KOD twitter feed stated 2 years ago :

Don't wait for me, I'm kind of like a Zombie. Go get Sublime Text @sublimehq which is awesome: http://www.sublimetext.com

I concur; Sublime Text is my current editor of choice.

Generators functions allow you to declare a function that behaves like an iterator, ie it can be used in a for loop. u can learn Here: generator

def generator(n):
        list_of = range(1,n+1)
        for i in list_of:
            if i % 7 == 0:
                yield i

    for i in generator(100):
        print i

or

You can use next(generator(100)) to print one element at top

or

list(generator(100))

When calling the generator function you receive generator object. In order to get values you should iterate over this object. In you case you can do list(generator(100))

But this doesn't make sense. Use list comprehension if you need list:

[x for x in range(1, 101) if x % 7 == 0]

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