我正在使用以下內容回圈訪問一些回傳的具有兩個欄位的 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'}]
最終格式正確,但資料不正確。我期待有一個包含兩個物件的陣列,兩個問題和答案。
uj5u.com熱心網友回復:
每次 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 中內置函式的名稱。input是一個通過控制臺接受用戶輸入的函式。myInput為了避免任何誤解,我已將其名稱更改為。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/447643.html
標籤:Python 数组 python-3.x for循环 目的
