【发布时间】:2014-03-26 04:05:11
【问题描述】:
def main():
score = 0
answers = ['B', 'D', 'A', 'A', 'C', 'A', 'B', 'A', 'C', 'D', 'B', 'C', 'D', 'A', 'D', 'C', 'C', 'B', 'D', 'A']
testA = open('newfile.txt', 'r')
for line in testA:
gr = str(line)
if gr == str(answers[line]):
score+=1
testA.close()
checkpass(score)
def checkpass(score):
if score >= 15:
print("You passed")
else:
print("You failed")
main()
我正在尝试编写一些 ^ 代码,该代码采用文本文件并将其条目与上面记录的列表进行比较。如果文本文件中的字母与同时索引的列表中的字母相同,则累加器应加一。为什么我不能检查 A == A 或 B==B 在列表中?有人可以解释我做错了什么吗?
【问题讨论】:
-
if gr == str(answers[line]):?你可能想要:if line in answers: -
我想你是说如果文件的第一行是
B,那么你想得分。如果第二行是D,则得分。一般来说,如果文件的第 n 行是answers中的第 n 个条目,则得分。从该规范开始,您可以开始编写代码。 -
我想检查 gr 是否等于索引 #line 处“答案”列表中的字符串字符..
-
是的,Raymond 这就是我想做的,但我希望我编写的代码能够完成这项任务。你能展示一下更好的方法吗?