[英]Why is my object being duplicated when I try to add it to an array?
I'm using the following to loop through some returned SQL data that has two fields.我正在使用以下循环遍历一些返回的具有两个字段的 SQL 数据。
cont = []
datarow = {}
for x in result:
input = x[0]
response = x[1]
datarow['input'] = input
datarow['response'] = response
print(datarow)
cont.append(datarow)
The result is结果是
{'input': 'do you have a pet?', 'response': 'yes, I have a dog'}
[{'input': 'do you have a pet?', 'response': 'yes, I have a dog'}]
{'input': "What is your dog's name?", 'response': 'Ringo'}
[{'input': "What is your dog's name?", 'response': 'Ringo'}, {'input': "What is your dog's name?", 'response': 'Ringo'}]
The eventual format is correct, but the data is not.最终格式正确,但数据不正确。 I was expecting to have an array with two objects in it, the two questions and answers.
我期望有一个包含两个对象的数组,两个问题和答案。
Each time the for loop runs, you assign the new item to the datarow
dictionary and the whole datarow
to the cont
list.每次 for 循环运行时,您将新项目分配给
datarow
字典,并将整个数据行cont
datarow
。 It would be best if you did something like:如果您执行以下操作,那将是最好的:
cont = []
for x in result:
datarow = {}
myInput = x[0]
response = x[1]
datarow['input'] = myInput
datarow['response'] = response
cont.append(datarow)
A side note: never use a name that previously has been assigned to an in-built function in python. input
is a function that takes input from the user through the console.旁注:切勿使用先前已分配给 python 中的内置 function 的名称。
input
是 function,它通过控制台从用户那里获取输入。 I have changed its name to myInput
in order to avoid any misunderstanding.为了避免任何误解,我已将其名称更改为
myInput
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.