Python append()正在将每个变量替换为新变量

Python append()正在将每个变量替换为新变量,python,append,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 ran

我有一个循环,在这个循环中我编辑一个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)

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

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

您可能有兴趣进一步阅读。

数据
是一个dict,这意味着它的值是通过引用传递的,您必须使用[copy.deepcopy()] ()如果要保持原始数据不静音:

from copy import deepcopy
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())
    # Create a shallow copy, modify it and append to new
    new_data = deepcopy(data)
    new_data["result"]["metadata"]["intentName"] = intent_names[random_index_IntentNames]
    new_data["sessionId"]=session_id[random_index_SessionIds]
    new_data["timestamp"] = timestamp
    dataNew.append(new_data)
json.dump(dataNew, outfile, indent=2)
注意:如果
数据
未存储可变项,则可以使用它来避免修改原始值


祝你好运

我自己找到了解决方案。我在循环中分配了“数据”,它起了作用:

json_data = open(filepath).read()
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 = json.loads(json_data)
     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)

数据
是字典对象。每次都要向同一个对象追加引用,因此如果更改dict,那么更改将反映在整个列表中(列表中的每个条目都指向同一个单独的字典)。您需要附加dict的深度副本,以便它们在内存中不是同一个对象。这基本上就是你链接到的答案。嗨@roganjosh。我是Python编程的初学者,这就是为什么我没有完全理解你的观点。如果您有一个解决方案,您能对我的代码进行更改,使其符合要求吗?它仍在替换旧的元素:/您能找到解决方案吗?我使用了copy.deepcopy()。即使不起作用:/@TonyMathew我已经更新了我的答案,它也应该起作用,但是如果它不起作用,这意味着数据会在代码的其他部分被修改。我使用了copy和deepcopy,但仍然没有work@TonyMathew很难说问题出在哪里。我上面的例子应该能代表我们在代码中看到的东西。如果在每次迭代中创建一个副本不起作用,那么您需要提供一个可重复的示例,我们可以在本地运行。