首页 > 解决方案 > 为什么在 HackerRank 中“NoneType”对象不可迭代,但 PyCharm 中不可迭代?

问题描述

使用 Python 3.x,我正在尝试根据老师奇怪的评分方式来汇总学生的成绩。基本上,如果学生成绩低于 38,则什么也不做。如果等级与下一个 5 的倍数之差小于 3,则将等级四舍五入到下一个 5 的倍数。否则,不要更改等级。以下是我在 PyCharm 和 HackerRank 的基于 Web 的 IDE 中使用的代码:

grades = [37, 39, 52, 83, 91]

def gradingStudents(grades):
    for i in range(len(grades)):
        grade = grades[i]
        if grade > 38:
            for j in range(4):
               next_val = grade + j
               if ((next_val-grade) < 3) and (next_val%5 == 0):
                   grade = next_val
        print(grade)

gradingStudents(grades)

PyCharm 中的输出是正确的:

37
40
52
85
91

作为比较,这里是来自 HackerRank ( https://www.hackerrank.com/ ) 中基于 Web 的 IDE 的代码:

#!/bin/python3
import os
import sys

#
# Complete the gradingStudents function below.
#
def gradingStudents(grades):
    for i in range(len(grades)):
        grade = grades[i]
        if grade > 38:
            for j in range(4):
               next_val = grade + j
               if ((next_val-grade) < 3) and (next_val%5 == 0):
                   grade = next_val
        print(grade)

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))) #<-- This is line 32 from error!
    f.write('\n')

    f.close()

这会引发以下错误:

Traceback (most recent call last):
File "solution.py", line 32, in <module>
f.write('\n'.join(map(str, result)))
TypeError: 'NoneType' object is not iterable

标签: pythonpython-3.xpycharm

解决方案


这是一种执行相同操作的列表理解方式:

def gradingStudents(grades):
    return [5 * (x // 5) + 5 if x > 38 and x % 5 > 2 else x for x in grades]

print(gradingStudents([37, 39, 52, 83, 91]))
# [37, 40, 52, 85, 91]

考虑到它是一种理解并且简洁,这将更有效。


推荐阅读