[英]formatted string of series of numpy array elements
It seems quit trivial to me but I'm still missing an efficient and "clean" way to insert a series of element belonging to numpy array (as aa[:,:]
) in a formatted string to be printed/written. 它似乎对我来说微不足道但我仍然缺少一种有效且“干净”的方式来插入属于numpy数组的一系列元素(如
aa[:,:]
)在要打印/写入的格式化字符串中。 In fact the extended element-by-element specification syntaxes like: 事实上,扩展的逐元素规范语法如下:
formattedline= '%10.6f %10.6f %10.6f' % (aa[ii,0], aa[ii,1], aa[ii,2])
file1.write(formattedline+'\n')
are working. 在工作中。
But I have not found any other shorter solution, because: 但我还没有找到任何其他更短的解决方案,因为:
formattedline= '%10.6f %10.6f %10.6f' % (float(aa[ii,:]))
file1.write(formattedline+'\n')
of course gives: TypeError: only length-1 arrays can be converted to Python scalars
当然给出:
TypeError: only length-1 arrays can be converted to Python scalars
or: 要么:
formattedline= '%10.6f %10.6f %10.6f' % (aa[ii,:])
file1.write(formattedline+'\n')
gives: TypeError: float argument required, not numpy.ndarray
. TypeError: float argument required, not numpy.ndarray
: TypeError: float argument required, not numpy.ndarray
。 I have tried with iterators but with no success. 我尝试过迭代器,但没有成功。
Of course this is interesting when there are several elements to be printed. 当然,当要打印几个元素时,这很有趣。
So: how can I combine iteration over numpy array and string formatted fashion? 那么:我怎样才能将迭代结合在numpy数组和字符串格式的时尚上?
You could convert it to a tuple: 你可以将它转换为元组:
formattedline = '%10.6f %10.6f %10.6f' % ( tuple(aa[ii,:]) )
In a more general case you could use a join
: 在更一般的情况下,您可以使用
join
:
formattedline = ' '.join('%10.6f'%F for F in aa[ii,:] )
If you are writing the entire array to a file, use np.savetxt: 如果要将整个数组写入文件,请使用np.savetxt:
np.savetxt(file1, aa, fmt = '%10.6f')
The fmt
parameter can be a single format, or a sequence of formats, or a multi-format string like fmt
参数可以是单个格式,也可以是格式序列,也可以是多格式字符串
'%10.6f %5.6f %d'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.