【问题标题】:Saving python lists data as 1 pickle and then loading them back将 python 列表数据保存为 1 个泡菜,然后将它们加载回来
【发布时间】:2021-05-09 08:37:14
【问题描述】:

在我正在处理的程序的一部分中,我想将 3 个列表保存到 1 个泡菜并在稍后的某个阶段将它们加载回这 3 个列表中,是否可以将 3 个列表保存到 1 个泡菜并阅读它们不知何故回来了? 很想得到一个如何解决这个问题的例子!

【问题讨论】:

    标签: python list pickle


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 2015-09-11
      • 1970-01-01
      • 2022-10-16
      • 2021-06-28
      相关资源
      最近更新 更多