问题
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