Python/Numpy问题。最后一年物理本科。。。我有一小段代码,它根据一个公式创建一个数组(本质上是一个n×n矩阵)。我将数组重塑为一列值,从中创建一个字符串,格式化它以删除多余的括号等,然后将结果输出到保存在用户文档目录中的文本文件中,然后由另一个软件使用。问题是高于“n”的某个值,输出只给出前三个值和后三个值,中间有“…”。我认为Python会自动删减最终结果以节省时间和资源,但是我需要在最终文本文件中包含所有这些值,不管处理需要多长时间,而且我一辈子都找不到如何阻止它这样做。相关代码复制到下面。。。你知道吗
import numpy as np; import os.path ; import os
'''
Create a single column matrix in text format from Gaussian Eqn.
'''
save_path = os.path.join(os.path.expandvars("%userprofile%"),"Documents")
name_of_file = 'outputfile' #<---- change this as required.
completeName = os.path.join(save_path, name_of_file+".txt")
matsize = 32
def gaussf(x,y): #defining gaussian but can be any f(x,y)
pisig = 1/(np.sqrt(2*np.pi) * matsize) #first term
sumxy = (-(x**2 + y**2)) #sum of squares term
expden = (2 * (matsize/1.0)**2) # 2 sigma squared
expn = pisig * np.exp(sumxy/expden) # and put it all together
return expn
matrix = [[ gaussf(x,y) ]\
for x in range(-matsize/2, matsize/2)\
for y in range(-matsize/2, matsize/2)]
zmatrix = np.reshape(matrix, (matsize*matsize, 1))column
string2 = (str(zmatrix).replace('[','').replace(']','').replace(' ', ''))
zbfile = open(completeName, "w")
zbfile.write(string2)
zbfile.close()
print completeName
num_lines = sum(1 for line in open(completeName))
print num_lines
任何帮助都将不胜感激!你知道吗
您不需要摆弄
numpy
数组的字符串表示形式。一种方法是使用tofile
:一般来说,如果只想写内容,就应该遍历数组/列表。你知道吗
输出:
但是使用
numpy
我们只需要使用tofile:输出与上述格式相同。你知道吗
在矩阵上调用
str
将为您提供与您尝试print
时得到的类似格式的输出,因此这就是您正在将格式化的截断输出写入文件的内容。你知道吗考虑到您正在使用python2,使用
xrange
将比使用rane(创建列表)更有效,也不建议使用冒号分隔多个导入,您可以简单地:import numpy as np, os.path, os
变量和函数名也应该使用下划线
z_matrix
、zb_file
、complete_name
等。。你知道吗相关问题 更多 >
编程相关推荐