【问题标题】:Comparing elements of numpy arrays in python比较python中numpy数组的元素
【发布时间】:2011-07-08 18:29:37
【问题描述】:

我想比较两个 1x3 数组,例如:

if output[x][y] != [150,25,75]

output 这里是 3x3x3,所以 output[x][y] 只是 1x3)。

我收到一条错误消息:

ValueError: The truth value of an array with more than one element is ambiguous. 

这是否意味着我需要这样做:

if output[y][x][0] == 150 and output[y][x][1] == 25 and output[y][x][2] == 75:

或者有更清洁的方法吗?

我正在使用 Python v2.6

【问题讨论】:

    标签: python arrays comparison numpy


    【解决方案1】:

    numpy的方式是使用np.allclose:

    np.allclose(a,b)
    

    虽然对于整数,

    not (a-b).any()
    

    更快。

    【讨论】:

      【解决方案2】:

      你也应该得到消息:

      使用 a.any() 或 a.all()

      这意味着您可以执行以下操作:

      if (output[x][y] != [150,25,75]).all():
      

      这是因为将 2 个数组或一个数组与一个列表进行比较会产生一个布尔数组。比如:

      array([ True,  True,  True], dtype=bool)
      

      【讨论】:

      • 我认为 .any 对于 != 和 .all 对于 == 更有意义。
      【解决方案3】:

      转换为列表:

      if list(output[x][y]) != [150,25,75]
      

      【讨论】:

      • 您还可以比较两个形状相同的数组,从而为您提供一组 True/False 值。
      【解决方案4】:

      你可以试试:

      a = output[x][y]
      b = [150,25,75]
      
      if not all([i == j for i,j in zip(a, b)]):
      

      【讨论】:

        猜你喜欢
        • 2017-01-19
        • 1970-01-01
        • 1970-01-01
        • 2019-11-12
        • 1970-01-01
        • 1970-01-01
        • 2018-09-29
        • 2021-06-24
        • 1970-01-01
        相关资源
        最近更新 更多