我是初学者,正在学习烧瓶。做运动时,我看不懂一些代码。谁能解释一下for循环这一行?
@app.route("/details/<int:pet_id>")
def pet_details(pet_id):
pet = next((pet for pet in pets if pet["id"] == pet_id), None)
if pet is None:
abort(404, description="No Pet was Found with the given ID")
return render_template("details.html", pet = pet)
我无法从代码中理解这一行
pet = next((pet for pet in pets if pet["id"] == pet_id), None)
答案 0 :(得分:3)
next
从生成器中获取下一项,在本例中为(pet for pet in pets if pet["id"] == pet_id)
。该生成器会将您的pet
对象的列表/集合减少为仅其ID与所请求的pet_id
相同的对象。
这里的None
是默认值:如果生成器没有下一个元素,则通常会抛出StopIteration
异常,但是在这种情况下,next
将处理该异常,而不会返回一个None
对象,而不是抛出错误