python - '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 :
我想这就是全部,感谢任何试图提供线索、元素或将为这个小程序做出贡献的人!
解决方案
你的第一个问题在这里:
content_line = []
for char in line:
content_line.append(char)
这些都不需要。只需line
用于接下来的几行:
for line in file:
if l == 0:
question.append(line)
ETC
推荐阅读
- python - Python 迭代工具
- android - Image Cropper 无法正常工作 - 为什么?
- python-3.x - 无监督 CNN keras 模型
- node.js - Docker:从一个容器到其他容器的http请求停滞不前
- spatstat - 'spatstat' 'envelope'-object 不能由 dclf.test 评估(错误:错误的行数)
- shell - 在 Jenkins Shell 脚本中设置一个新的环境变量
- selenium - 通过 Canvas 标签实现图形自动化
- compiler-errors - Msys2 -> f951.exe:致命错误:在第 2 行第 1 列读取模块“...”:意外 EOF
- java - 数据存储查询超时
- mysql - 在此祖先链查询中接受 id 列表而不是一个