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

时间:2017-05-27 09:43:02

标签: python append

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

这是我的代码:

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)

3 个答案:

答案 0 :(得分:2)

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

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

您可能会对Is Python call-by-value or call-by-reference? Neither.感兴趣,以便进一步阅读。

答案 1 :(得分:2)

public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { if request.url?.scheme == "myapp" { // UIApplication.shared.open(request.url!, options: [:], //completionHandler: nil) let myVC: MyAnotherController = MyAnotherController() self.present(myVC, animated: true) { } return false } return true } 是一个字典,这意味着它是mutable并且它的值是通过引用传递的,你必须使用[copy.deepcopy()] (https://docs.python.org/2/library/copy.html#copy.deepcopy)如果你想保持原始数据不被静音:

data

注意:如果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) 不存储可变项,则可以使用dict.copy以避免修改原始值。

祝你好运!

答案 2 :(得分:0)

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

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)
相关问题