python - Pickle 仅保存几对用户输入列表中的最后一对输入
问题描述
我遇到了一个问题,pickle 模块只保存用户输入的最后一对输入。
我怎样才能使泡菜模块保存每对输入(一对问题和答案),而不仅仅是输入的最后一个?
import pickle
import random
import os
os.system('cls')
n = input("How many questions do you have? : ")
vvff = list()
for i in range(0, int(n)):
v = input("Enter question : ")
while True:
f = input("Enter answer ((true) or (false)) : ")
if f.lower() in ('true', 'false'):
break
else:
print("Invalid answer")
for i in range(0, int(n)):
vf = {"question": v, "answer": f}
vvff.append(vf)
question_vff = input("Would you like to save (yes or no)")
if (question_vff == 'yes'):
pickle.dump(vvff, open("Savequestionandanswerlist.dat", "wb"))
pickle.dump(n, open("Savequestionamount.dat", "wb"))
print("Saved!")
if (question_vff == 'no'):
print ("Please save to use this information,")
解决方案
问题是您没有在主循环中添加问题和答案。当您在主循环之外执行循环时,变量v
和f
设置为发出的最后一个问题和答案。当您知道自己拥有它们时,只需将它们添加到您的列表中:
...
for i in range(0, int(n)):
v = input("Enter question : ")
while True:
f = input("Enter answer ((true) or (false)) : ")
if f.lower() in ('true', 'false'):
# We have our question, along with a valid answer so add them to our list!
vf = {"question": v, "answer": f}
vvff.append(vf)
break
else:
print("Invalid answer")
question_vff = input("Would you like to save (yes or no)")
...
推荐阅读
- c++ - 当结构是赋值的右值时,返回结构内变量的值
- python - 如何使用 Keras 的深度学习模型解决不适合 imagenet 数据集的问题?
- postgresql - Postgres Timescale DB 中的更新
- android - flutter build apk --split-per-abi:app-armeabi-v7a-release.apk和app.apk有什么区别
- reactjs - 样式不适用于 css 组合器 + 带有 makeStyles() material-ui 的伪类
- c++ - 更新后 OpenCV Cpp 代码未在 Ubuntu 20.04 中运行
- python-3.x - Selenium 点击循环忽略了一些值
- python - 为什么在弹性搜索中点击 api 时索引会继续创建
- r - 尝试使用 Rticles 生成示例 R 降价时出错:找不到 pdflatex Ubuntu 20.04
- android - android:autoLink 在 Android 的 ButtonView 中不起作用?