使用“收率"来表示.在功能上 [英] Using "yield" in a function

查看:109
本文介绍了使用“收率"来表示.在功能上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在使用yield生成1个参数n的函数中生成类似的内容:

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

那是我最后的尝试:

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

这就是我收到的:

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

推荐答案

您的错误在这里:

for i in n:

n是整数,并且不是可迭代的.也许您想使用 xrange() (仅适用于Python 2)或 range() (在Python 3上推荐)在这里:

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):

请注意,这将从 0 开始迭代,而不是1(直到并包括n - 1).您可以使用range(1, n + 1),也可以直接在总和中加1:

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

这实际上与生成器没有任何关系.无论您是否使用过yield,尝试遍历普通的int对象都不会起作用.

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.

这篇关于使用“收率"来表示.在功能上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆