【问题标题】:How do I check the values of an array in numpy?如何检查numpy中数组的值?
【发布时间】:2021-05-21 03:12:19
【问题描述】:

我的代码有问题的部分是:

history = np.array([[0, 0, 1, 1],[1, 0, 0, 1]])
opponentsActions = history[1]
if opponentsActions == [0, 0, 0, 0]:
    print("nice")

我得到的错误是: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

【问题讨论】:

标签: python arrays numpy


【解决方案1】:

当您执行检查时,您会收到表示比较的数组

>>> opponentsActions == [0, 0, 0, 0]
array([False,  True,  True, False])

系统会提示您使用 any() 或 all(),这是一个非常有用的提示。 All(something) 表示您要检查的某物的所有元素都必须为真。所以在你的情况下:

>>> np.all(opponentsActions == [0, 0, 0, 0])
False

【讨论】:

  • 感谢您的解释,但因为这是一个 if 语句,所以二战给出的“答案”更正确。还是谢谢
【解决方案2】:

您正在将一个 numpy 数组与 Python 列表进行比较,这是行不通的,一个快速的解决方法是使用要比较的 tolist() 将 numpy 数组转换为 python 列表,它会这样工作,看看:

history = np.array([[0, 0, 1, 1],[0, 0, 0, 0]])
opponentsActions = history[1]
print(opponentsActions)
if opponentsActions.tolist() == [0, 0, 0, 0]:
     print("nice")

或者您可以按照 SebaLenny 的建议使用 np.all。

【讨论】:

  • 这可能是一种解决方法,但更简单和更短的替代方法就像 wwii 写道:“if (opponentsActions == [0, 0, 0, 0]).all():"
  • 一定会的!
猜你喜欢
  • 2020-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
  • 2020-03-15
  • 1970-01-01
  • 2014-11-01
  • 1970-01-01
相关资源
最近更新 更多