list.append() 将每个变量替换为新变量

Ton*_*hew 2 python append

我有一个循环,在其中编辑 json 对象并将其附加到列表中。但是在循环之外,所有旧元素的值都会更改为新元素我的问题与这里
的问题 类似 ,但我仍然找不到问题的解决方案。

这是我的代码:

json_data = open(filepath).read()
data = json.loads(json_data)
dataNew=[]

#opening file to write json  
with open(filepath2, 'w') as outfile:
for i in range(50):
    random_index_IntentNames = randint(0,len(intent_names)-1)
    random_index_SessionIds = randint(0,len(session_id)-1)
    timestamp = strftime("%Y-%m-%d %H:%M:%S", gmtime())
    data["result"]["metadata"]["intentName"] = intent_names[random_index_IntentNames]
    data["sessionId"]=session_id[random_index_SessionIds]
    data["timestamp"] = timestamp
    dataNew.append(data)
json.dump(dataNew, outfile, indent=2)
Run Code Online (Sandbox Code Playgroud)

rog*_*osh 5

列表中的每个项目只是对内存中单个对象的引用。与链接答案中发布的内容类似,您需要附加字典的副本。

import copy

my_list = []

a = {1: 2, 3: 4}
b = a # Referencing the same object
c = copy.copy(a) # Creating a different object

my_list.append(a)
my_list.append(b)
my_list.append(c)

a[1] = 'hi' # Modify the dict, which will change both a and b, but not c

print my_list
Run Code Online (Sandbox Code Playgroud)

您可能对Python 是按值调用还是按引用调用感兴趣?两者都不。供进一步阅读。