2016-04-21 73 views
1

循環腳本執行一個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很陌生。感謝你的幫助。

+0

你可能想['itertools.groupby'](https://docs.python.org/3.5/library/itertools.html#itertools.groupby )將第一列的記錄分組。 – ChrisP

回答

0

一種方法是遍歷記錄兩次:

for operation, value, answer in allRecords: 
    if answer == 'correct': 
     print 'correct' 

for operation, value, answer in allRecords: 
    if answer != 'correct': 
     print (operation, value, answer) 
0

你可以先全部添加的一個子集,然後得到該子集中的正確答案。

# Filter all additions from the results 
additions = [[o, v, a] for o, v, a in results if o == 'add'] 

# Filter the addition with the correct answer 
correct = [v for o, v, a in additions if a == 'correct'] 

# Output information 
print "Correct : {}".format(correct) 
for addition in additions: 
    print "{}, {}, {}".format(addition[0], addition[1], addition[2]) 

上述輸出碼,

Correct : ['c'] 
add, a, wrong 
add, b, wrong 
add, c, correct 
add, d, wrong