【问题标题】:Pickle all variables腌制所有变量
【发布时间】:2020-09-19 23:35:43
【问题描述】:

我正在寻找一种方法来按排序顺序腌制所有变量及其值。我正在尝试以下方法:

预期结果:将 va 的值附加到 totalList ,然后将 vb's 值..等等。然后将totalList 转储到pickle 文件中。

import pickle
import time
import os
import re

v0 = ["r0", "hello","hello there","hi there","hi", "hey","good to see you"]
v1 = ["r1", "how are you", "how do you do","how are you doing", "how you doing"]
v2 = ["r2", "What's up" , "what is up" , "what's up bro"]
v10 = ['r10', 'who made you', 'who built you', 'who is your creator']


imports = "pickle","time","os","re"
totalList = []
for key in dir():
    if key.startswith("__") == 0 and key not in imports:
        print(globals()[key])
        totalList.append(globals()[key])
# print(totalList) # getting weird values

with open('queryList.pkl', 'wb') as f:
    pickle.dump(totalList, f)

我得到这样的结果:

>> ('pickle', 'time', 'os', 're')
>> []
>> ['r0', 'hello', 'hello there', 'hi there', 'hi', 'hey', 'good to see you']
>> ['r1', 'how are you', 'how do you do', 'how are you doing', 'how you doing']
>> ['r10', 'who made you', 'who built you', 'who is your creator']
>> ['r2', "What's up", 'what is up', "what's up bro"]

我想去掉('pickle', 'time', 'os', 're')[] 的结果,并在追加到totalList 之前对结果进行排序,或者在迭代之前对其进行排序。

【问题讨论】:

  • 排序顺序是什么?变量名?
  • 是的,v0、v1、v2、v10
  • 所以它是变量的数字名称而忽略了第一个字符?因为简单的 lex。 order 会将 v10 放在 v2 之前。
  • 哦,好吧..我用字母重命名了变量,现在排序问题解决了。如何摆脱这些不需要的结果:('pickle', 'time', 'os', 're'), [<built-in function vars>]

标签: python sorting variables pickle var


【解决方案1】:

这是一种做你想做的事的方法。你应该忽略一些你不感兴趣的变量——特别是importstotalList

ignore_list = [ "ignore_list", "totalList"]
totalList = []

for key in dir():
    if not key.startswith("__") and key not in ignore_list and type(globals()[key]) != type(pickle):
        print(key)
        totalList.append(globals()[key])

totalList = sorted(totalList, key=lambda x: int(x[0][1:]) )

结果是:

[['r0', 'hello', 'hello there', 'hi there', 'hi', 'hey', 'good to see you'],
 ['r1', 'how are you', 'how do you do', 'how are you doing', 'how you doing'],
 ['r2', "What's up", 'what is up', "what's up bro"],
 ['r10', 'who made you', 'who built you', 'who is your creator']]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-29
    • 2018-08-21
    • 2014-04-23
    • 2011-10-01
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    相关资源
    最近更新 更多