python - 为什么在 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
解决方案
这是一种执行相同操作的列表理解方式:
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]
考虑到它是一种理解并且简洁,这将更有效。
推荐阅读
- vue.js - 我应该在 vue.js 中转储 data 属性中的所有变量吗
- python - 在字符串中查找单词
- android - 如何从视图模型中获取 val 中的编辑文本文本
- angular - npm -g @angular/cli (11.2) 错误
- php - 如何让 phpMyAdmin 显示旧数据
- firebase-authentication - 带有firebase auth的剃须刀页面-在哪里放置这个令牌?:)
- c - AVR ATmega328p 和 MCP3201 问题
- lisp - 输入数字的平均值
- python-3.x - RFID (MFRC522) 扫描仪等待读取或写入 Raspberry PI
- python - 如何将链接保存在 .txt 文件中?