Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python +;的操作数类型不受支持:';numpy.float64';和';str';_Python_Numpy - Fatal编程技术网

Python +;的操作数类型不受支持:';numpy.float64';和';str';

Python +;的操作数类型不受支持:';numpy.float64';和';str';,python,numpy,Python,Numpy,我试图从一个输入文件(input.txt)中找到标准偏差和平均值,该文件在一列中包含5000个数据,我希望在文件“outfile.txt”中输出。我的代码如下: 进口numpy 从numpy进口* def main(): main() 在执行Python2.7.1时,出现以下消息:TypeError:不支持+的操作数类型:'numpy.float64'和'str' 但是,如果在屏幕上打印输出而不是输出文件,则以下代码运行良好: import numpy from numpy import * D

我试图从一个输入文件(input.txt)中找到标准偏差和平均值,该文件在一列中包含5000个数据,我希望在文件“outfile.txt”中输出。我的代码如下:

进口numpy

从numpy进口*

def main():

main()

在执行Python2.7.1时,出现以下消息:TypeError:不支持+的操作数类型:'numpy.float64'和'str'

但是,如果在屏幕上打印输出而不是输出文件,则以下代码运行良好:

import numpy
from numpy import *
DataIn = loadtxt('input.txt')
s = DataIn.std()
print s
让我帮助您获取正确的代码。

请尝试以下操作:

outfile.write(str(s) + '\n')
outfile.write(str(m) + '\n')
试试这个:

outfile.write(str(s) + '\n')
outfile.write(str(m) + '\n')

第一种情况失败,因为
s+'\n'
尝试添加两个不同类型的参数,并且两个函数都不能用来实现这个(
numpy.float64.\uuuuuuuuuuu
str.\uuuuuu radd\uuuuuuu
)知道如何添加
numpy.float64
str
。你必须明确,要么自己用

outfile.write(str(s) + '\n')
或者使用不同的功能。最好是这样:

outfile.write( "{0}\n".format(s) )
第二种情况之所以成功,是因为
print
语句隐式调用了传递给它的每个表达式上的
str
),因此它的工作方式就像您编写了

print str(s)
不涉及加法运算符,因此不需要未定义的隐式转换

请注意,如果
numpy.float64.\uuuu add\uuuuu
的定义如下,则第一种情况可以工作

def __add__(self, x):
    if isinstance(x, str):
        return str(self) + x
    ...

第一种情况失败,因为
s+'\n'
尝试添加两个不同类型的参数,并且两个函数都不能用来实现这个(
numpy.float64.\uuuuuuuuuuu
str.\uuuuuu radd\uuuuuuu
)知道如何添加
numpy.float64
str
。你必须明确,要么自己用

outfile.write(str(s) + '\n')
或者使用不同的功能。最好是这样:

outfile.write( "{0}\n".format(s) )
第二种情况之所以成功,是因为
print
语句隐式调用了传递给它的每个表达式上的
str
),因此它的工作方式就像您编写了

print str(s)
不涉及加法运算符,因此不需要未定义的隐式转换

请注意,如果
numpy.float64.\uuuu add\uuuuu
的定义如下,则第一种情况可以工作

def __add__(self, x):
    if isinstance(x, str):
        return str(self) + x
    ...

您是否希望输出具有特定的位数?如果是,则更换管路

outfile.write(s + '\n')
outfile.write(m + '\n')
用例如

outfile.write('{:1.4f}\n'.format(s))
outfile.write('{:1.4f}\n'.format(m))

这将为您提供浮点数后有4位数字的数字。请参见

是否有您希望输出的特定位数?如果是,则更换管路

outfile.write(s + '\n')
outfile.write(m + '\n')
用例如

outfile.write('{:1.4f}\n'.format(s))
outfile.write('{:1.4f}\n'.format(m))
这将为您提供浮点数后有4位数字的数字。看