Using “yield” in a function

2019-09-10 11:09发布

问题:

I want to generate something like that in a function that receives 1 argument n using yield to generate:

      1
     1+2
    1+2+3
      …
      …
1+2+3+⋯+n−1+n

That is my last try:

def suite(n):
    total = 0
    for i in n:
        total+=i
        yield total

and this is what I receive:

Traceback (most recent call last):
  File "notebook", line 4, in suite
TypeError: 'int' object is not iterable

回答1:

Your error is here:

for i in n:

n is an integer and not an iterable. Perhaps you wanted to use xrange() (Python 2 only) or range() (recommended on Python 3) here:

for i in range(n):

Note that this starts iteration at 0, not 1 (up to and including n - 1). You could either use range(1, n + 1), or simply add 1 to your sum:

def suite(n):
    total = 0
    for i in range(n):
        total += i + 1
        yield total

This hasn't really got anything to do with generators; wether or not you used yield, trying to loop over a plain int object doesn't work either way.



回答2:

Because your function declaration doesn not correspond with for loop. You cannot iterate over integer, you should use some iterable instead. The simplest way is to use range:

The correct version is:

def suite(n):
    total = 0
    for i in range(n):
        total += i
        yield total
>>>suite(6)

Or, you can do another change to yield sum of some iterable:

def suite(iterable):
    total = 0
    for i in iterable:
        total += i
        yield total

>>>suite([1,2,3])


回答3:

Use range to create an iterator to use in your for loop:

def suite(n):
    total = 0
    for i in range(1, n+1):
        total+=i
        yield total