【问题标题】:The truth value of an array with more than one element is ambiguous (numerical)具有多个元素的数组的真值不明确(数值型)
【发布时间】:2014-02-10 21:16:16
【问题描述】:

我遇到了一个错误,无法找到解决方案。这是我的功能:

def rep(N,list,t):
     result=0
     for i in range(N):
         if((list[i]-t)<=t):
             result = result + 1
         else:
             result = result + 0
     return(result/N) 

然后我尝试绘制函数:

 plt.plot(x,rep(1000,nEchant,x))

这就是我得到的:

 Traceback (most recent call last):
   File "<pyshell#114>", line 1, in <module>
     plt.plot(x,rep(1000,nEchant,x))
   File "<pyshell#113>", line 4, in rep
     if((list[i]-1)<=t):
 ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

谢谢!

【问题讨论】:

  • 在您的定义中,避免调用第二个参数list,因为这会影响内置函数。你能展示一下nEchant 的样子吗?
  • x 是一个列表\数组,我假设因为您试图针对它进行绘图。在函数中变为 t。也许你想要 t[i] 在那里?
  • rep只返回一个值,如果它可以工作的话。这是故意的吗?绘制单个值似乎有点傻。
  • 如果 t 是一个列表,在两个列表之间会出现 - 错误。
  • @njzk2 正确,但它们可能是 numpy 数组。 OP,请回答问题,并显示更多代码。试图解决一半缺失的难题,效率不高。

标签: python random numpy scipy


【解决方案1】:

看起来表达式 (list[i]-t)&lt;=t 正在返回一个 numpy 数组。要确保list[i]-t所有 值小于t,请使用:

numpy.all((list[i]-t)<=t)

【讨论】:

    猜你喜欢
    • 2019-03-19
    • 2020-03-15
    • 1970-01-01
    • 2019-08-21
    • 2021-07-06
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多