Python修改JSON文件中演员列表值无变化问题求解
问题原因及修复方案
根因说明
你使用的for x in movie["actors"]遍历方式中,x只是列表元素的临时值拷贝,且字符串属于Python不可变类型,直接对x重新赋值只会修改x这个临时变量的指向,不会改动原列表存储的内容,因此修改后打印列表没有变化。
修复实现
方案1:按索引遍历修改原列表(推荐,仅修改匹配项,无额外内存开销)
import json path = 'movie_1.txt' # 读取JSON文件,推荐用with上下文自动管理文件句柄 with open(path, encoding="utf-8") as f: movie = json.load(f) print("修改前:", movie['actors']) # 用enumerate同时获取索引和值,匹配后直接修改原列表对应位置 for idx, actor in enumerate(movie["actors"]): if actor == "Alan Arkin": movie["actors"][idx] = "John Doe" print("修改后:", movie['actors']) # 若需要将修改后的内容同步回原文件,取消注释以下代码即可 # with open(path, "w", encoding="utf-8") as f: # json.dump(movie, f, ensure_ascii=False, indent=2)
方案2:列表推导式生成新列表(代码更简洁)
# 读取JSON代码同上 movie["actors"] = [actor if actor != "Alan Arkin" else "John Doe" for actor in movie["actors"]]
内容的提问来源于stack exchange,提问作者Shaun22
相关产品推荐
相关产品推荐

