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

Why is my object being duplicated when I try to add it to an array?

我正在使用以下循环遍历一些返回的 SQL 具有两个字段的数据。

cont = []
datarow = {}

for x in result:
    input = x[0]
    response = x[1]

    datarow['input'] = input
    datarow['response'] = response
    print(datarow)
    cont.append(datarow)

结果是

{'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'}]

最终格式正确,但数据不正确。我期待有一个包含两个对象的数组,两个问题和答案。

每次 for 循环运行时,您将新项目分配给 datarow 字典,并将整个 datarow 分配给 cont 列表。如果你做这样的事情会更好:

cont = []

for x in result:
  datarow = {}
  myInput = x[0]
  response = x[1]
  
  datarow['input'] = myInput
  datarow['response'] = response
  cont.append(datarow)

旁注:切勿使用先前已分配给 python 中的 in-built 函数的名称。 input 是一个通过控制台获取用户输入的函数。为了避免误会,我把名字改成了myInput