簡體   English   中英

當我嘗試將它添加到數組時,為什么我的 object 被復制了?

[英]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字典,並將整個數據行cont datarow 如果您執行以下操作,那將是最好的:

cont = []

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

旁注:切勿使用先前已分配給 python 中的內置 function 的名稱。 input是 function,它通過控制台從用戶那里獲取輸入。 為了避免任何誤解,我已將其名稱更改為myInput

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM