【发布时间】:2018-08-09 02:13:12
【问题描述】:
我有这个代码:
import sys
from scipy.stats import binom
def mcnemar_midp(b, c):
n = b + c
x = min(b, c)
dist = binom(n, .5)
p = 2. * dist.cdf(x)
midp = p - dist.pmf(x)
return midp
#get numbers from user
num1 = sys.argv[1]
num2 = sys.argv[2]
# calculate the result
myresult = mcnemar_midp(num1, num2)
# Display the sum
print myresult
如果我这样称呼它是行不通的: python mcnemar.py 87 89
但是,如果我为 num1 和 num2 硬编码 2 个值,它可以正常工作。我得到的错误如下:
Traceback (most recent call last):
File "mcnemar.py", line 28, in <module>
myresult = mcnemar_midp(num1, num2)
File "mcnemar.py", line 19, in mcnemar_midp
p = 2. * dist.cdf(x)
File "/usr/lib/python2.7/dist-packages/scipy/stats/distributions.py", line 440, in cdf
return self.dist.cdf(x, *self.args, **self.kwds)
File "/usr/lib/python2.7/dist-packages/scipy/stats/distributions.py", line 6635, in cdf
k = asarray((k-loc))
TypeError: unsupported operand type(s) for -: 'numpy.ndarray' and 'numpy.ndarray'
但只有当我尝试从命令行传递数字时,如果我将它们写在代码中,它就可以工作。 请帮助我,我是 python 新手!
【问题讨论】:
-
num1和num2如果您将它们作为命令行参数传递给脚本,它们将是字符串。错误信息对我来说没有多大意义,但我敢打赌,如果你使用num1 = int(sys.argv[1])和num2 = int(sys.argv[2]),你的问题就会消失 -
@juanpa.arrivillaga 是正确的。该错误是有道理的,因为如果
b和c是字符串,n = b + c和x = min(b, c)仍然有效。 -
@GJJ 是的,我测试过了。问题是错误消息有点模糊。
-运算符支持类型ndarray和ndarray,但不如果这些数组的dtypes不兼容,例如object和int。但是错误信息有点笼统。但是当我尝试重现它时,我会得到类似TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U12') dtype('<U12') dtype('<U12')的东西确实 有意义,但也许这是numpy版本问题。我在'1.11.3' -
好的,你能写出解决方案作为答案并接受它还是删除问题?
标签: python