让我困惑的Python列表索引超出范围错误

0 投票
1 回答
47 浏览
提问于 2025-04-14 17:10

我正在尝试制作一个Flask应用程序,作为我课堂的最终项目。现在快到最后阶段了,但遇到了一个让我困惑的错误。我对Python还很陌生,希望这里面有我遗漏的基本问题...

因为是Flask,所以有很多html文件与之相关,这让我们很难在这里复现一个简单的例子。不过,基本问题是这样的:

在这个函数中

@app.route('/view_meal', methods=['GET', 'POST'])
def view_meal():
  if request.method == 'POST':
    selected_meal_id = request.form['selected_meal']
    #get all the food_items associated with this meal
    rows = display_table('meal', where_condition=f"id = '{selected_meal_id}'")
    food1 = display_table('food_item', where_condition=f"id = '{rows[4]}'")
    food2 = display_table('food_item', where_condition=f"id = '{rows[5]}'")
    food3 = display_table('food_item', where_condition=f"id = '{rows[6]}'")
    food4 = display_table('food_item', where_condition=f"id = '{rows[7]}'")
    food5 = display_table('food_item', where_condition=f"id = '{rows[8]}'")
    foods = [food1, food2, food3, food4, food5]
    return render_template('display_meal.html', rows = rows, foods=foods)
  else:
    rows = display_table('meal')
    return render_template('view_meal.html', items=rows) 

在我第一次尝试时,我只是获取与不同食物相关的id_numbers,这个过程很顺利。所以我知道我从表单中正确获取了selected_meal_id,而且这一行

rows = display_table('meal', where_condition=f"id = '{selected_meal_id}'")

也确实在正确查询数据库。display_table函数只是一个简单的SELECT * FROM,并传入了表名和WHERE条件。

为了进一步测试,我在一个单独的小Python文件中查询了我正在使用的meal_id

result = cur.execute("SELECT * FROM meal WHERE id='PCKCMH0S'").fetchall()
print(result)

结果是这样的

[('PCKCMH0S', 'English Breakfast', 'Fatty', '3/9/2024', 'BQD3MPHM', '77WWB0BQ', 'QGH6DV8S', 'I4VD1IE7', 'QGH6DV8S')]

所以这就是应该在rows中的内容。

但是这一行

food1 = display_table('food_item', where_condition=f"id = '{rows[4]}'")

却抛出了一个list index out of range的错误,rows[4]被标记了。这里面我漏掉了什么呢?rows里应该有九个元素。

1 个回答

0
rows = [('PCKCMH0S', 'English Breakfast', 'Fatty', '3/9/2024', 'BQD3MPHM', '77WWB0BQ', 'QGH6DV8S', 'I4VD1IE7', 'QGH6DV8S')]

这是一个只包含一个元组的列表。rows[4] 是在尝试从这个外层列表中获取第五个元素,但因为这个列表里只有一个元素,所以会出错。

解决办法是先获取那个元组,然后再去访问元组里的元素。可以这样做:

rows = display_table('meal', where_condition=f"id = '{selected_meal_id}'")
row = rows[0]

food1 = display_table('food_item', where_condition=f"id = '{row[4]}'")
food2 = display_table('food_item', where_condition=f"id = '{row[5]}'")

撰写回答