Python生成器在每次调用时产生相同的值 [英] Python generator yields same value each call

查看:53
本文介绍了Python生成器在每次调用时产生相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望生成器从列表中产生每个连续值的余弦值,但是每次都得到相同的值.

I want this generator to yield the cosine of each successive value from a list, but am getting the same value each time.

import math     
angles = range(0,361,3)

# calculate x coords:    
def calc_x(angle_list):
    for a in angle_list:
        yield round(radius * cos(radians(a)), 3) 

每次调用都产生相同的值:为什么会这样,我该如何解决?

Yields the same value with each call: Why is this and how do I fix it?

>>>calc_x(angles).next()
5.0
>>>calc_x(angles).next()
5.0
>>>calc_x(angles).next()
5.0

推荐答案

每次调用 calc_x 时,都会创建一个 new 生成器.您需要做的是创建一个,然后继续使用它:

Every time you call calc_x you create a new generator. What you need to do is create one and then keep using it:

calc = calc_x(angles)
next(calc)
next(calc)
# etc.

这篇关于Python生成器在每次调用时产生相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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