【问题标题】:Comparing lists - Homework Python比较列表 - 作业 Python
【发布时间】:2011-07-14 02:56:47
【问题描述】:
 correct_ans = ['B', 'D', 'A', 'A', 'C', 'A', 'B', 'A', 'C', 'D', 'B', 'C', \
               'D', 'A', 'D', 'C', 'C', 'B', 'D', 'A']

这是我从 txt 文件中导入列表的声明

 # import user answers into a list
 infile = open('testscores.txt', 'r')
 driver_ans = infile.readlines()
 infile.close()

 driver_ans = ['B', 'D', 'A', 'A', 'C', 'B', 'B', 'A', 'C', 'D', 'B', 'C', \
               'D', 'A', 'D', 'C', 'C', 'B', 'D', 'A']

    for index in range(0, 20):
         if driver_ans[index] == correct_ans[index]:
             total_correct += 1
         else:
             wrong_ans.append(index + 1)

这个逻辑继续返回所有都是错误的答案。从视觉上比较我的“correct_ans”列表和“driver_ans”列表是不正确的。我究竟做错了什么?!

【问题讨论】:

  • 这取决于。你的代码的其余部分是什么样的?我们不知道driver_ans 或correct_ans 里面是什么。
  • 您能否将它们显示为 driver_ans 和 correct_ans 的值
  • @hyperboreus 我已更新并包含我的列表内容
  • 首先从文件中读取driver_ans,然后手动设置? testcores.txt 有什么格式?每行一个答案?如果是这种情况,请记住,您从文件中读取的答案将以换行符结尾,因此我们都错了,如 'A\n' != 'A'。
  • @hyperboreus:这正是问题所在,我已经剥离了 \n 并且它工作正常!再次感谢您!

标签: list python-3.x compare


【解决方案1】:

只是猜测。如果testscores.txt有内容

B
D
A
A
...

请记住,driver_ans 将是

['B\n', 'D\n', 'A\n', 'A\n', ...

试试吧

driver_ans = [x.strip ('\n') for x in infile.readlines()]

【讨论】:

  • 谢谢!我找错地方了……我没有 .rstrip 字符。我纠正了这一点,你是对的!我工作完美!非常感谢!
【解决方案2】:

readlines() 函数返回包含尾随换行符的行。所以,试试吧:

driver_ans = [x.strip() for x in infile.readlines()]

【讨论】:

  • 谢谢!这就是问题所在,一旦我被指出不是我的 if/else 逻辑的方向,我就看到了我的错误!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多