繁体   English   中英

numpy数组的类似Python列表的字符串表示形式

[英]Python list-like string representation of numpy array

考虑有一些相当长的numpy数组:

importy numpy as np;
long_array1 = np.array([random.random() for i in range(10000)]);
long_array2 = np.array([random.random() for i in range(10000)]);
long_array3 = np.array([random.random() for i in range(10000)]);

我想将数组保存到文件file.dat ,每个numpy数组一行。 数组的文本表示应采用类似于python数组的格式,即在以下numpy数组的情况下:

a = np.array([0.3213,0.145323,0.852,0.723,0.421452])

我想将以下行保存在文件中。

[0.3213,0.145323,0.852,0.723,0.421452]

我在做什么:

array1_str = ",".join([str(item) for item in long_array1]);
array2_str = ",".join([str(item) for item in long_array2]);
array3_str = ",".join([str(item) for item in long_array3]);

with open("file.dat","w") as file_arrays:
    file_arrays.write("[" + array1_str + "]\n");
    file_arrays.write("[" + array2_str + "]\n");
    file_arrays.write("[" + array3_str + "]\n");

实际上一切正常。 我只是对代码的效率感到怀疑。 我几乎可以肯定,必须有另一种(更好,更高效)的方法来做到这一点。 我也欢迎对随机列表生成发表评论。

这是最快的方法:

','.join(map(str, long_array1.tolist()))

如果要使文本更紧凑,这也很快:

','.join(map(lambda x: '%.7g' % x, long_array1.tolist()))

资料来源:我以此为基准对pycollada库的维护者进行了测试。

由于您希望使用类似Python列表格式的格式,因此如何实际使用Python列表格式呢?

array1_str = repr(list(long_array1))

那将主要留在C-land,性能应该会好得多。

如果您不想使用空格,请在以下时间取出它们:

array1_str = repr(list(long_array1)).translate(None, " ")

但是,内存使用可能是一个问题。

听起来您可能可以为此使用numpy.savetxt()

就像是:

def dump_array(outfile, arraylike):
    outfile.write('[')
    numpy.savetxt(outfile, arraylike, newline=',', fmt="%s")
    outfile.write(']\n')

虽然我不认为相应的numpy.loadtxt()能够以这种格式读取。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM