【问题标题】:Python, compare n by m numpy array with n sized numpy arrayPython,将 n x m numpy 数组与 n 大小的 numpy 数组进行比较
【发布时间】:2018-12-09 12:15:34
【问题描述】:

我正在做一个编程项目,但由于某种原因我被卡住了。

gradeList = [-3,0,2,4,7,10,12]

    for i1 in range(np.size(grades,1)-1):
        for i2 in range(np.size(grades,0)-1):
            for i3 in range(len(gradeList)-1):
                if grades[i1,i2] != gradeList[i3]:
                    print(grades[i1,i2])
                    print(i1,i2,i3)
                    print("This is an error"+str(grades[i1,i2]))
                else:
                    print("FINE")

我正在尝试为我的gradeList 中的每个值检查n x m 数组中的每个值,最终我想打印不在gradeList 中的n x m 数组中的等级位置。我收到以下错误代码:

IndexError: index 3 is out of bounds for axis 1 with size 3

我的成绩数组:

 grades = np.array([[  7.    7.    4. ],[ 12.   10.   10. ],[ -3.    7.    2. ],[ 10.   12.   12. ],[ 12.   12.   12. ],[ 10.   12.   12. ],[ -3.8   2.2  11. ],[ 20.   12.6 100. ],[  4.   -3.    7. ],[ 10.   10.   10. ],[  4.   -3.    7. ],[ 10.   10.   10. ],[ 10.   10.   10. ],[ 12.   12.   12. ],[ -3.   -3.   -3. ],[ 20.   12.6 100. ]])

【问题讨论】:

  • 您的成绩定义中有语法错误
  • 哦,是的,我明白了,但我只是把它放在那里让你们知道我使用的是什么数字。我会改变它

标签: python arrays list numpy compare


【解决方案1】:

我认为问题出在:

# i1 => [0,1]
# i2 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
# i3 => [0, 1, 2, 3, 4, 5]

当您调用 grades[i1,i2] 时,您可以拥有 grades[0,3] 并且超出范围,因为该轴包含三个元素。

我想解决方案是将 grades[i1,i2] 更改为 grades[i2,i1] 它出现的位置(三次)。

【讨论】:

    【解决方案2】:

    您交换了 i1i2 的定义,这会导致您遇到错误。以下是修复代码的方法:

    for i1 in range(grades.shape[0]):
        for i2 in range(grades.shape[1]):
            for i3 in range(len(gradeList)):
                if grades[i1,i2] != gradeList[i3]:
                    print(grades[i1,i2])
                    print(i1,i2,i3)
                    print("This is an error"+str(grades[i1,i2]))
                else:
                    print("FINE")
    

    上面代码中的grades.shape[0] 等同于您原始代码中的np.size(grades, 0)grades.shape[0] 是比较常用的成语。

    此外,我已从您的范围定义中删除了所有 -1 调整。如果你有这些,它将阻止你的循环到达数组中的最后一个值。 range 的行为是它会在一个值达到您设置的最大值之前停止它。

    例如,list(range(len(gradeList))) 将返回 gradeList 的完整索引集:

    [0, 1, 2, 3, 4, 5, 6]
    

    list(range(len(gradeList - 1))) 将省略最后一个索引:

    [0, 1, 2, 3, 4, 5]
    

    【讨论】:

      猜你喜欢
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 2020-07-20
      • 2014-07-11
      • 2011-06-14
      • 1970-01-01
      相关资源
      最近更新 更多