无法保留文字游戏的结果

Unable to Retain the Result of a Word Game

我创建了一个非常简单的文字游戏。您一次浏览一个单词列表,如果您知道该单词,则可以继续下一个单词,或者如果您不知道该单词,则可以将其保存到您的新单词列表中。 只要是 运行,脚本就可以正常工作,但是一旦我退出游戏,我就会丢失所有保存的单词,新单词列表将变为空。 我尝试使用泡菜,但没有成功。这是我的代码:

my_list = ['cat', 'dog', 'duck', 'tiger', 'puppy']
new_word = []

def get_item(a_list):
    ind = 0
    while ind < len(my_list):
        confirm_list = ['y', 'Y']
        confirm_list2 = ['n', 'N']
        confirm_list3 = ['y', 'Y', 'n', 'N']
        confirm = input('Type Y to continue or N to quit: ')
        if confirm in confirm_list:
            print(my_list[ind])
            ind += 1
            confirm_add = input('Type Y to add this word to New_Word list: ')
            if confirm_add in confirm_list:
                new_word.append(my_list[ind - 1])
                for item in new_word:
                    print(item)
            if ind == len(my_list):
                print('This is the last item.')
        if confirm in confirm_list2:
            print('Thanks for playing. See you again.')
            break
        if confirm not in confirm_list3:
            print('Please type Y or N in small or capital letters.')

get_item(my_list)

您需要将项目保存到磁盘并在再次打开程序时重新加载它。

Try a tutorial

您在 python 中的对象(例如您的列表)都是临时的,它们存在于内存中,一旦您退出 Python 或 Python 程序,它们就会消失创建了它们。

所以请改用 Pickle

>>> your_list = ["cat","dog"]
>>>
>>> import pickle
>>> 
>>> with open('your_list.pkl', 'wb') as f:
...   pickle.dump(your_list, f)
... 

然后退出程序再打开。现在输入

>>>import pickle
>>>with open('your_list.pkl','rb') as f:
...    your_newlist = pickle.load(f)
...
>>>your_newlist
["cat","dog"]

为了让你更清楚

你有一个函数def get_item(a_list):
在函数的最后使用

return list_you_need_to_store

然后使用返回的 list.

按照我给出的代码示例进行操作