Python yield 语句每次都返回相同的值

标签 python yield next

编辑:我想使用 next 语句查看解决方案。 我正在访问一个返回json对象的天气应用API,该对象的部分信息是每天的日出和日落时间,这里是它的内容(三天):

my_dict = {
"daily": [
    {
      "dt": "2020-06-10 12:00:00+01:00",
      "sunrise": "2020-06-10 05:09:15+01:00",
      "sunset": "2020-06-10 19:47:50+01:00"
    },
    {
        "dt": "2020-06-11 12:00:00+01:00",
        "sunrise": "2020-06-11 05:09:11+01:00",
        "sunset": "2020-06-11 19:48:17+01:00"
    },
    {
      "dt": "2020-06-12 12:00:00+01:00",
      "sunrise": "2020-06-12 05:09:08+01:00",
      "sunset": "2020-06-12 19:48:43+01:00"
    }
]
}

这里的函数应该每天返回一个元组,但它没有。它不断返回同一天的数据元组,第一天。

daily_return = my_dict['daily']


def forecast(daily_return):
    # daily_return is a list
    for day in daily_return:
        # day becomes a dict
        sunrise = day['sunrise']
        sunset = day['sunset']
        yield sunrise, sunset

for i in range(3):
    print(next(forecast(daily_return)))

这是输出:

('2020-06-10 05:09:15+01:00', '2020-06-10 19:47:50+01:00')
('2020-06-10 05:09:15+01:00', '2020-06-10 19:47:50+01:00')
('2020-06-10 05:09:15+01:00', '2020-06-10 19:47:50+01:00')

最佳答案

因为您每次循环时都在启动生成器,而不是循环一个范围,所以只需迭代生成器:

for sunrise, sunset in forecast(daily_return):
    print(sunrise, sunset)

如果你只想要前 3 个,你可以用一个范围压缩它或使用 itertools.islice 如@cs95 所示:

for sunrise, sunset, _ in zip(forecast(daily_return), range(3)):
    print(rise, set)

如果你必须使用 next 然后在循环外启动生成器:

gen = forecast(daily_return)
for i in range(3):
    print(next(gen))

您也可以使用 operator.itemgetter 来实现相同的功能,而不是您的自定义函数:

from operator import itemgetter
from itertools import islice

forecast_gen = map(itemgetter('sunrise', 'sunset'), daily_return)

for sunrise, sunset in islice(forecast_gen, 3):
    print(sunrise, sunset)

关于Python yield 语句每次都返回相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62310514/

相关文章:

python - 用 ":"连接子列表

python - 获得 `n` 独立几何随机变量之和的最快方法

ruby-on-rails - Rails yield 和 content_for 部分

python - 在 Python 中处理时,如何确保任意函数调用列表不会急切地评估超过短路点?

python - 在循环中跳过多次迭代

python - python/matlab/simulink/maple 用户的 Modelica?

Python asyncio、futures 和 yield from

c - 读取一行时 c 中的段错误

angular - 如何在 Angular 中使用 subscribe-next RxJS?

python - celery worker 不工作虽然 rabbitmq 有队列建立