【问题标题】:What does it mean - TypeError: only length-1 arrays can be converted to Python scalars?这是什么意思 - TypeError:只有长度为 1 的数组可以转换为 Python 标量?
【发布时间】:2014-02-19 22:10:40
【问题描述】:

我正在尝试将使用 lambda 关键字定义的函数传递给绘图函数,但我收到 TypeError 消息。我的相关代码是这样的:

y = lambda z: dot_epsilon(z) * (math.exp(-tau(z))/H_z(z).value)
plot(y,100, 5e6)

def plot(function, min_x, max_x):
    t = np.logspace(min_x, max_x, 1000)
    s = function(t)
    plt.plot(t, s, 'b-', lw=2)

我收到此错误消息:

  File "mucalc.py", line 160, in <lambda>
    y = lambda z: dot_epsilon(z) * (math.exp(-tau(z))/H_z(z).value)
TypeError: only length-1 arrays can be converted to Python scalars

在这种情况下,这个 TypeError 代表什么?

【问题讨论】:

    标签: python python-2.7 numpy


    【解决方案1】:

    您正在使用math.exp,它只接受一个浮点数。请改用np.exp

    这是因为math.exp(x) 试图调用x.__float__(),如果xnp.ndarray,那么它的__float__ 是这样实现的:

    def __float__(self):
        if len(self) is 1:
            return self.flatten()[0]
        else:
            raise TypeError, 'only length-1 arrays can be converted to Python scalars'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-27
      • 2013-03-15
      • 1970-01-01
      • 2016-08-06
      • 2018-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多