我有一个问题。这可能很容易,但无论如何我找不到一个好主意。问题是我有2个python程序。第一个是提供 2 个输出,其中一个输出是一个巨大的列表(就像有数千个其他列表),另一个是 Weka 的简单 csv 文件。我需要以某种方式存储此列表(第一个输出),以便稍后能够将其用作其他程序的输入。我不能只将其发送到第二个程序,因为当第一个程序完成时,Weka 还应该为第二个程序生成新的输出。因此,第二个程序必须等待第一个程序和Weka的输出。
问题是输出列表由丢失的具有数值的列表组成。简单的例子可以是:
list1 = [[1,5,7],[14,3,27], [19,12,0], [23,8,17], [12,7]]
如果我将其写入 txt 文件,那么当我尝试读取它时,它将所有值作为字符串。是否有任何简单快捷的方法(因为数据很大)来管理以某种方式将所有值作为整数?或者也许在第一种情况下,将其写为整数?
最佳答案
我认为这是使用 pickle module 的好例子
保存数据:
import pickle
lst = [[1,5,7],[14,3,27], [19,12,0], [23,8,17], [12,7]]
pickle.dump(lst, open('data.pkl', 'wb'))
从保存的文件中读取数据:
import pickle
lst = pickle.load(open('data.pkl', 'r')
来自文档:
The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” [1] or “flattening”, however, to avoid confusion, the terms used here are “pickling” and “unpickling”.
还有更快的 cPickle module :
保存数据:
from cPickle import Pickler
p = Pickler(open('data2.pkl', 'wb'))
p.dump(lst)
从保存的文件中读取数据:
from cPickle import Unpickler
up = Unpickler(open('data.pkl', 'r'))
lst = up.load()
关于python - 存储列表,然后将其作为整数读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18999870/