2014-03-26 87 views
2

考虑有几个相当长numpy的数组:Python列表类的字符串表示

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"); 

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

+0

你想要解决什么问题?什么是阅读这些文件? – SingleNegationElimination

+0

我将在稍后分析数据 - 绘制图表,计算概率等。问题是已经有几个模块使用指定的格式,所以我想保持相同的格式,以便于以下处理。不过,你推荐哪种格式(供我未来使用)? CSV格式可能是最好的一般兼容性。但是,有什么格式建议在Python中使用(由python写入文件,由python读取,由python处理...)? – Marek

+0

另外:你通常会写'np.random.random(10000)',而不是在列表理解中调用Python的标准随机函数,然后调用'np.array'。它既短又快。 – DSM

回答

4

这是最快的方法:

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

如果你想保持文本更加紧凑​​,这是太快太:

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

来源:我为基准此每一个可能的方法为pycollada图书馆的维护者。

2

既然你想要一个类似Python的列表格式,那么实际使用Python列表格式呢?

array1_str = repr(list(long_array1)) 

这是要留大多是在C-土地和性能都要好得多。

如果你不希望的空间,带着他们出去后:

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

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

0

听起来像你可能可以使用numpy.savetxt()这个;

类似:

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

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