保存 python 将数据列为 1 个 pickle,然后将它们加载回去

Saving python lists data as 1 pickle and then loading them back

在我正在处理的程序的一部分中,我想将 3 个列表保存到 1 个 pickle 并在稍后的某个阶段将它们加载回这 3 个列表,是否可以将 3 个列表保存到 1 个 pickle 和以某种方式读回它们? 很想得到一个如何处理这个的例子!

保存您的多个列表,例如3 在你的情况下,在单个 pickle 文件中,你必须将所有列表放入字典中,然后保存单个字典。加载字典后重新加载您想要的列表。

import pickle

def SaveLists(data):
    open_file = open('myPickleFile' "wb")
    pickle.dump(data, open_file)
    open_file.close()

def LoadLists(file):
    open_file = open(file, "rb")
    loaded_list = pickle.load(open_file)
    open_file.close()
    return loaded_list

#example to call the functions
cars = ['Toyota', 'Honda']
fruits = ['Apple', 'Cherry']

#create dictionary and add these lists
data = {}
data['cars'] = cars
data['fruits'] = fruits #add upto any number of lists

#save the data in pickle form
SaveLists(data)

#Load the data when desired
lists = LoadLists('myPickleFile')
print(lists['fruits']) #get your desired list