简体   繁体   English

当我尝试将它添加到数组时,为什么我的 object 被复制了?

[英]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.

相关问题 当我尝试使用默认构造函数实例化对象时,为什么会根据调用的参数化构造函数收到错误消息? - Why am I getting an error based on my parameterized constructor being called when I try to instantiate an object using my default constructor? 当我尝试添加新对象时,为什么会出现错误? - Why do I get an error when I try to add a new object? 为什么当我尝试向其形状添加更多内容时,我的乌龟停止移动? - Why does my turtle stop moving when I try to add more to its shape? 为什么“current_question”被视为一个对象? 当我运行我的代码时,它说 type(str) - Why is "current_question" being treated as an object? When I run my code it says type(str) 为什么我的文本被复制而不是包装在 pygame 中? - Why is my text being duplicated instead of wrapped in pygame? 当我尝试将重启 function 添加到我的程序 PYTHON 时出现错误 - Errors when I try to add restart function to my program PYTHON 当我尝试使用 corsheaders 时,为什么我的应用程序会中断? - Why does my application break when I try to use corsheaders? 尝试打印列表内容时,为什么要打印索引? - Why is my index printing when I try to print the contents of the list? 为什么在尝试附加Python时我的列表没有加入 - Why my lists are not Joining When I try to Append Them Python 当我在管道上尝试 LabelEncoder 时,为什么管道会抛出 FitFailedWarining? - Why is pipeline throwing FitFailedWarining when I try LabelEncoder on my pipeline?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM