2016-04-21 70 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