Python generator yields same value each call

天涯浪子 提交于 2021-01-27 16:11:48

问题


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

回答1:


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.


来源:https://stackoverflow.com/questions/15216972/python-generator-yields-same-value-each-call

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!