python - 存储列表,然后将其作为整数读取

标签 python file-io integer

我有一个问题。这可能很容易,但无论如何我找不到一个好主意。问题是我有2个python程序。第一个是提供 2 个输出,其中一个输出是一个巨大的列表(就像有数千个其他列表),另一个是 Weka 的简单 csv 文件。我需要以某种方式存储此列表(第一个输出),以便稍后能够将其用作其他程序的输入。我不能只将其发送到第二个程序,因为当第一个程序完成时,Weka 还应该为第二个程序生成新的输出。因此,第二个程序必须等待第一个程序和Weka的输出。 flow graph

问题是输出列表由丢失的具有数值的列表组成。简单的例子可以是:

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/

相关文章:

arrays - 如何在 Matlab 中的单元格数组中查找唯一单元格(数字不是字符串)

python - 找到小于 n 的最大素数,其中 n = ~10^230

python - 使用 Python GTK+ 3 将对话框按钮居中对齐

python - 使用 NLTK 自定义 POS 标记(错误)

java - 打开命名管道时 FileInputStream 在构造函数上阻塞

c - 为什么 C 的 "fopen"将 "const char *"作为它的第二个参数?

java - 如何检查文本板中的下一个空行并附加下一个输入

java:将整数作为无符号 8 位整数写入文件

ios - 我应该在 iPhone/iPad 类中使用 NSNumber 还是 int?

python - 在Python中处理unicode转换