首页 > 解决方案 > 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,")

标签: pythonpython-3.x

解决方案


问题是您没有在主循环中添加问题和答案。当您在主循环之外执行循环时,变量vf设置为发出的最后一个问题和答案。当您知道自己拥有它们时,只需将它们添加到您的列表中:

    ...
    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)")
    ...

推荐阅读