【问题标题】:Can Python Pickle conserve object and variable types when dumping lists?Python Pickle 在转储列表时可以保存对象和变量类型吗?
【发布时间】:2019-06-11 16:11:11
【问题描述】:

我目前正在连接到远程数据库并查询一长串项目。我不知道数据库总共有多少项目,但我一直在查询适合我搜索的各种参数的大约 3000 个项目。获得所需的项目 ID 后,我会在数据库中查询每个项目的信息,类型如下:

[str, str, datetime, str, str, int, int, int, str, str, bool]

问题是,请求所有这些信息需要将近 45 分钟,因为数据库非常大。为了解决这个问题,我正在尝试 Pickle 列表,以便在尝试测试和调试其他 90% 的代码时暂时跳过查询步骤。我的大部分代码都在这个列表上执行操作,但我需要这个列表来测试这些操作。

我相信可以只键入 cast 每个项目字段,然后将其放回到我的主列表中,但这似乎效率很低。下面是处理收集/酸洗的代码,以及我必须执行的示例操作。

query_object = QueryObject()
item_ids = query_object.get_ids()
print("\nFinished collecting the ID's for", len(item_ids), "items.")
answer = input("Do you wish to load information from the disk or the database? (d = disk, i = database)\n")
if answer == "d":
    file = open('item_information.txt', 'rb')
    items_list = pickle.load(file)
    # pickle loads everything in as a string, so currently I just manually cast each item in the list
    for item in items_list:
        item = [str(item[0]), str(item[1]), str(item[2]), str(item[3]), int(item[4]), int(item[5]), int(item[6]),
                int(item[7]), str(item[8]), str(item[9]), bool(item[10])]
    file.close()
elif answer == "i":
    file = open('item_information.txt', 'wb')
    items_list = query_object.gather_item_list_data(item_ids)
    pickle.dump(items_list, file)
    file.close()
else:
    print("Bad input.", answer)
    sys.exit(1)

# remove all items that aren't usable
items_list[:] = [item for item in items_list if item[9] is True]

有没有办法让 Pickle 也转储列表格式,这样当我 pickle.load() 时,我的列表输入方式与 pickle.dump()ed 时相同?

【问题讨论】:

  • 如果 pickle 将所有内容都加载为字符串,那是因为您将所有内容都保存为字符串。只是不要那样做。请注意,您的 for 循环不会修改您正在加载的列表...

标签: python list type-conversion pickle


【解决方案1】:

Pickle 通常会加载您转储的任何内容,包括类型信息。例如:

所以我不确定你的问题是什么,我希望这取决于你实际倾销的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 2022-01-08
    • 1970-01-01
    相关资源
    最近更新 更多