>编辑:我想使用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)
我建议将forecast
转换为对单个条目进行操作的函数。然后,您可以调用map
来获取迭代器并对其调用next
:
def forecast(day):
return day['sunrise'], day['sunset']
it = map(forecast, daily_return)
print(next(it))
# ('2020-06-10 05:09:15+01:00', '2020-06-10 19:47:50+01:00')
如果要从迭代器中获取 X 个条目,请使用islice
:
from itertools import islice
list(islice(map(forecast, daily_return), 3))
# [('2020-06-10 05:09:15+01:00', '2020-06-10 19:47:50+01:00'),
# ('2020-06-11 05:09:11+01:00', '2020-06-11 19:48:17+01:00'),
# ('2020-06-12 05:09:08+01:00', '2020-06-12 19:48:43+01:00')]
重新创建生成器 3 次,然后生成相同的第一个元素 3 次。在循环之前创建生成器。简单总比复杂好。
x = forecast(daily_return))
for i in range(3):
print(next(x))