无法通过for循环将值分配给数组

时间:2019-05-07 21:13:53

标签: python python-3.x

我想通过将值舍入到5来从另一个数组返回一个新数组,如果舍入的数字小于40,则不应该舍入。 但显示“ IndexError:列表分配索引超出范围”错误。

import os
import sys

#
# Complete the gradingStudents function below.
#
def gradingStudents(grades):
    def round_to_next5(n):
        return n + (5 - n) % 5
    j = len(grades)
    r = [j]
    for i in range(0,len(grades)):
        roundi = round_to_next5(grades[i])
        dif = roundi - grades[i]
        if dif < 3 and roundi > 40:
            r[i] = roundi
            print("working1")
        else:
            r[i] = grades[i]
            print("working2")
    return r
if __name__ == '__main__':
    f = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    grades = []

    for _ in range(n):
        grades_item = int(input())
        grades.append(grades_item)

    result = gradingStudents(grades)

    f.write('\n'.join(map(str, result)))
    f.write('\n')

    f.close()

期望数组,但显示错误。

2 个答案:

答案 0 :(得分:0)

尝试这个。 r = [j]是错误的元凶。我已经使用numpy创建了一个zeros数组,如果您没有numpy,请通过以下命令pip install numpy

安装它

完整的工作代码如下。

    import os
    import sys
    from numpy import zeros
    #
    # Complete the gradingStudents function below.
    #
    def gradingStudents(grades):
        def round_to_next5(n):
            return n + (5 - n) % 5
        j = len(grades)
        r = zeros(j)
        for i in range(0,len(grades)):
            roundi = round_to_next5(grades[i])
            dif = roundi - grades[i]
            if dif < 3 and roundi > 40:
                r[i] = roundi
                print("working1")
            else:
                r[i] = grades[i]
                print("working2, i: ", i)
        return r
    if __name__ == '__main__':
        f = open('text.txt', 'w')

        n = int(input())
        print('Got user input')
        grades = []

        for _ in range(n):
            grades_item = int(input())
            grades.append(grades_item)

        print('Len of grades is: ', len(grades))
        result = gradingStudents(grades)

        f.write('\n'.join(map(str, result)))
        f.write('\n')

        f.close()

答案 1 :(得分:0)

您的IndexError的最可能原因是对r[i]的一项分配。每当grades的长度大于1时,都会导致此错误。问题是r初始化为包含单个数字(等级长度)的列表。

我认为您打算将r初始化为长度为j的列表,不包含j,例如:

r = [0 for _ in range(j)]