该脚本执行SQL查询并返回如下结果:
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 :(得分: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)
答案 1 :(得分: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