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

1 投票
3 回答
2494 浏览
提问于 2025-04-18 03:00

我正在尝试从一个输入文件(input.txt)中计算标准差和平均值,这个文件里有5000个数据,都是一列的。我希望把结果输出到另一个文件(outfile.txt)中。我的代码如下:

import numpy

from numpy import *

def main():
    outfile = open('outfile.txt','w')
    DataIn = loadtxt('input.txt')
    s = DataIn.std()
    m = DataIn.mean()
    outfile.write(s + '\n')
    outfile.write(m + '\n')
    outfile.close()

main()

当我在python 2.7.1中运行时,出现了以下错误信息:TypeError: unsupported operand type(s) for +: 'numpy.float64' and 'str'

不过,如果把输出直接打印在屏幕上,而不是输出到文件,下面的代码就能正常工作:

import numpy
from numpy import *
DataIn = loadtxt('input.txt')
s = DataIn.std()
print s

让我来帮你找到正确的代码。

3 个回答

1

你想要输出的数字有特定的位数吗?如果有的话,可以把下面的代码替换掉

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

比如可以改成

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

这样做会让你得到的小数点后有4位数字。想了解更多,可以查看这个字符串格式化的例子

1

第一个例子失败了,因为 s + '\n' 试图把两种不同类型的东西加在一起,而能处理这个加法的函数(numpy.float64.__add__str.__radd__)都不知道怎么把 numpy.float64str 加在一起。你需要明确地告诉程序怎么做,可以自己用 str 来转换,像这样:

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

或者使用其他的函数。像下面这样会更好:

outfile.write( "{0}\n".format(s) )

第二个例子成功了,因为 print 语句会自动对传给它的每个表达式调用 str,所以它的效果就像你写了:

print str(s)

在这个过程中,加法运算符没有参与,所以不需要进行任何不明确的隐式转换。

注意,如果 numpy.float64.__add__ 被定义成某种方式,第一个例子也可能会成功,像这样:

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

试试这个:

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

撰写回答