【发布时间】:2021-05-09 08:37:14
【问题描述】:
在我正在处理的程序的一部分中,我想将 3 个列表保存到 1 个泡菜并在稍后的某个阶段将它们加载回这 3 个列表中,是否可以将 3 个列表保存到 1 个泡菜并阅读它们不知何故回来了? 很想得到一个如何解决这个问题的例子!
【问题讨论】:
在我正在处理的程序的一部分中,我想将 3 个列表保存到 1 个泡菜并在稍后的某个阶段将它们加载回这 3 个列表中,是否可以将 3 个列表保存到 1 个泡菜并阅读它们不知何故回来了? 很想得到一个如何解决这个问题的例子!
【问题讨论】:
保存您的多个列表,例如3 在您的情况下,在单个泡菜文件中,您必须将所有列表放入字典中,然后保存单个字典。加载字典后,加载您想要的列表。
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
【讨论】: