【问题标题】:What is this error in passing arguments in python? [duplicate]在 python 中传递参数时这个错误是什么? [复制]
【发布时间】: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 新手!

【问题讨论】:

  • num1num2 如果您将它们作为命令行参数传递给脚本,它们将是字符串。错误信息对我来说没有多大意义,但我敢打赌,如果你使用 num1 = int(sys.argv[1])num2 = int(sys.argv[2]),你的问题就会消失
  • @juanpa.arrivillaga 是正确的。该错误是有道理的,因为如果 bc 是字符串,n = b + cx = min(b, c) 仍然有效。
  • @GJJ 是的,我测试过了。问题是错误消息有点模糊。 - 运算符支持类型ndarrayndarray,但如果这些数组的dtypes不兼容,例如objectint。但是错误信息有点笼统。但是当我尝试重现它时,我会得到类似TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('&lt;U12') dtype('&lt;U12') dtype('&lt;U12') 的东西确实 有意义,但也许这是numpy 版本问题。我在'1.11.3'
  • 好的,你能写出解决方案作为答案并接受它还是删除问题?

标签: python


【解决方案1】:

在将 sys.argv 值转换为整数后,该问题已得到解决。

【讨论】:

    猜你喜欢
    • 2010-11-13
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 2015-07-05
    • 2016-03-24
    相关资源
    最近更新 更多