首页 > 解决方案 > 'with open' 的问题,在 python 中创建一个微不足道的挑战

问题描述

我想创造一个微不足道的挑战!但它不像我想的那样工作。这是我的代码:

import os
with open('questions','r') as file:
   l = 0
   question = []
   right_guess = []
   wrong_guess_1 = []
   wrong_guess_2 = []
   for line in file:
        content_line = []
        for char in line:
             content_line.append(char)
        if l == 0:
             question.append(content_line)
             l = 1
        elif l == 1:
             right_guess.append(content_line)
             l = 2
        elif l == 2:
             wrong_guess_1.append(content_line)
             l = 3
        elif l == 3:
             wrong_guess_2.append(content_line)
             l = 4
   if l == 4:
        break
   print(question)
   print(right_guess)
   print(wrong_guess_1)
   print(wrong_guess_2)
   input('Awnser : ')

好的,现在让我解释一下这两个问题。我用这个问题文件结构尝试了我的代码(没有扩展,它只是“问题”):

 a question
      the right anwser
      false guess
      false guess
 a other question
      the right anwser
      false guess
      false guess

这是一个例子,如果你不明白:

 How does 1 + 1 ?
  3
  0
  5

显然答案是第二行:3!(开个玩笑,它是 2,我知道 :D )所以,让我们回到我们的问题:我已经启动了代码,它给了我这个结果:

 [[ 'H', 'o', 'w', ' ', 'd', 'o', 'e', 's', ' ', '1', '+', '1', ' ', '?', '\n']]
 [[ 'H', 'o', 'w', ' ', 'd', 'o', 'e', 's', ' ', '1', '+', '1', ' ', '?', '\n']]
 [[ 'H', 'o', 'w', ' ', 'd', 'o', 'e', 's', ' ', '1', '+', '1', ' ', '?', '\n']]
 [[ 'H', 'o', 'w', ' ', 'd', 'o', 'e', 's', ' ', '1', '+', '1', ' ', '?', '\n']]
 Answer :

我真的不明白问题出在哪里,但我希望有人能帮助我得到这个结果:

 How does 1+1 ?
 2
 0
 5
 Answer

如果有些人会看这个页面真的很疯狂,我可以期待得到这样的结果:

 (the program take one question, randomly, in the whole file)
 the chosen one
 one of the three possibles guests
 one other of the three possibles guests
 a third possible guest
 ( And we don't know which one is the correct )
 Answer :

我想这就是全部,感谢任何试图提供线索、元素或将为这个小程序做出贡献的人!

标签: pythonpython-3.x

解决方案


你的第一个问题在这里:

content_line = []
for char in line:
    content_line.append(char)

这些都不需要。只需line用于接下来的几行:

for line in file:
    if l == 0:
        question.append(line)

ETC


推荐阅读