尝试在 python 列表理解中使用 if/then 语句更新/添加到 JSON 元素。我设置 JSON 键“first_seen”的第一部分失败了。有什么想法吗?
now = datetime.datetime.now().strftime("%B, %d, %Y")
[obj["last_seen"] = now for obj in ref_db if obj['user']==user else add_new(user, ext_source, source, first_seen, now)]
错误是:
[obj["last_seen"] = now for obj in ref_db if obj['user']==user else add_new(user, ext_source, source, first_seen, now)]
^
SyntaxError: invalid syntax
我从错误中了解到我的语法错误,但我无法弄清楚为什么会出错。不能在列表理解中使用等号 (=) 吗?
感谢您的帮助。
最佳答案
List-Comprehensions 用于创建列表。您只想使用 for 循环:
now = datetime.datetime.now().strftime("%B, %d, %Y")
for obj in ref_db:
if obj['user'] == user:
obj["last_seen"] = now
else:
add_new(user, ext_source, source, first_seen, now)
关于python - 更新 Python 列表理解中的 JSON 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53141578/