python - 当会话对象是列表时如何修改烧瓶会话对象
问题描述
我有一个 Session 对象作为列表,我想在列表中更新它。我试图迭代 Flask Session 对象并且它有效,但是当我尝试修改 Flask Session 中的值时,它给了我一个错误。
@app.route("/")
def index():
if "lenta" not in session:
session["lenta"] = [[None, None, None], [None, None, None], [None, None, None]]
session["move"] = "X"
return render_template("game.html", game=session["lenta"], move=session["move"])
@app.route("/play/<int:row>/<int:col>")
def play(row, col):
for i in session["lenta"]:
for j in i:
session["lenta"][i][j] = row, col
redirect(url_for("index"))
我希望session["lenta"][i][j]
它将使用 HTML 中的值 Row 和 Col 进行更新,但我收到错误消息:
session["lenta"][i][j] = row, col
TypeError: list indices must be integers or slices, not list
解决方案
看起来您正在迭代session['lenta']
(ie for i in session["lenta"]
) 的元素,但 session["lenta"] 的元素本身就是列表(例如[None, None, None]
)。这就是您收到此错误的原因。
要解决它,请尝试调用您正在迭代的元素,如下所示:
def play(row, col):
for el in session["lenta"]:
for j, _ in enumerate(el):
el[j] = row, col
redirect(url_for("index"))
看看这是否有效,祝你好运!
[为澄清而编辑]:我没有你的全部代码,我检查过的是:
z = [[None, None, None], [None, None, None], [None, None, None]]
for vi in z:
for j,vj in enumerate(z):
vi[j] = (i,j)
(在 Python 3.6 上)
推荐阅读
- javascript - onclick html标签或在javascript中获取它
- node.js - 使用node js命令执行sql文件
- java - 仅用双引号之外的字典替换字符
- openshift - 容器中的 Filenet - IBM Content Navigator 和 Task Manager pod 的自定义 PVC 配置
- reactjs - React json对象值不显示
- python - 无法使用 bs4 中的 css 选择器一次选择所有标记元素
- azure-machine-learning-service - 从 AzureML 管道步骤中获取当前工作区
- stata - 用条件递归定义Stata中的变量
- google-apps-script - 如何在谷歌表格中将日期和时间转换为纪元
- python-3.x - 有没有更好的方法来获取驱动器 ID?