我想要比较列表中的字符串,但是当我输出它时,它会将正确的列表与其他列表的相同字符串进行20次比较。如果我能得到一些帮助,看看我做错了什么,我将不胜感激
def main():
submitted = ['A','D','C','A','C','A','D','C','A','D','A','C','B','D','A','C','C','A','D','B']
outfile = open('submitted.txt', 'w')
for item in submitted:
outfile.write(item + '\n')
outfile.close()
infile = open('submitted.txt', 'r')
submitted = infile.readlines()
infile.close()
sub_count = 0
while sub_count < len(submitted):
submitted[sub_count] = submitted[sub_count].rstrip('\n')
sub_count += 1
print 'The answers you submitted were ', submitted
print '******************************************************************************************'
correct = ['A','C','A','A','D','B','C','A','C','B','A','D','C','A','D','C','B','B','D','A']
outfile = open('correct.txt', 'w')
for item in correct:
outfile.write(item + '\n')
outfile.close()
infile = open('correct.txt', 'r')
correct = infile.readlines()
infile.close()
cor_count = 0
while cor_count < len(correct):
correct[cor_count] = correct[cor_count].rstrip('\n')
cor_count += 1
print 'The correct answers are ', correct
print '******************************************************************************************'
print 'BELOW IS THE COMPARISON OF YOUR ANSWERS TO THE CORRECT ANSWERS'
correct_count = 0
incorrect_count = 0
number_questions = 0
while (number_questions < 20):
number_questions += 1
for ans in submitted:
for cor in correct:
if cor == ans:
print cor, ans ,' = correct'
correct_count += 1
elif cor != ans:
incorrect_count += 1
print cor, ans ,' = wrong'
main()
答案 0 :(得分:2)
您希望迭代匹配对的所有提交/正确答案对。而是使用:
for ans, cor in zip(submitted, correct):
if ans == cor:
# do stuff
else:
# do other stuff
此外,直接删除此外的while
循环;它什么都没做。