循環腳本執行一個SQL查詢並返回類似下面的結果:通過結果通過SQL查詢預讀,而在Python
subtract,'a','wrong'
subtract,'b','wrong'
add,a,'wrong'
add,b,'wrong'
add,c,'correct'
add,d,'wrong'
subtract,'a','wrong'
subtract,'b','wrong'
我循環來一行行讀它,每個元素存儲在可變的,但這是我不知道下一步該做什麼的地方。
flag = 0
for rec in allRecords:
operation = rec[0]
value = rec[1]
answer = rec[2]
#if flag == 1:
#pass
#else:
if operation == 'add':
#start an inside loop to 'read ahead' and continue if operation == 'add' and stop when operation != 'add'
#find 'c' inside this loop and get the 'correct' element which is next to it and store in a new variable.
#break the loop to go back to main loop
#getVar = 'correct'
#print(getVar)
#flag = 1
else:
flag = 0
#after breaking out of the loop above, continue to the next records
print(rec)
所需的輸出:
correct
add,a,'wrong'
add,b,'wrong'
add,c,'correct'
add,d,'wrong'
我爲什麼這樣做呢? 我想先顯示正確答案,然後列出其餘選項。還在練習編程。
我爲什麼在這裏問? 我已經耗盡了所有資源,而且我很困難,需要指導。我搜索了從我所做的所有試驗和錯誤中收到的所有錯誤,但無法找到答案。
試過我最好解釋一下。我對編程和剛剛學習python很陌生。感謝你的幫助。
你可能想['itertools.groupby'](https://docs.python.org/3.5/library/itertools.html#itertools.groupby )將第一列的記錄分組。 – ChrisP