3 回答

TA貢獻1802條經驗 獲得超10個贊
使用模%5 應該可以幫助你。模是除法后得到的余數。示例8 % 5=3此外,//運算符在除法后會自動為您舍入
grades = [1, 9, 37, 38, 43, 47, 49, 99, 91]
rounded_grades = [grade if grade < 38 or grade % 5 in [0, 1, 2] else 5 * (grade // 5 + 1) for grade in grades]
print(grades)
print(rounded_grades)
#Output
[1, 9, 37, 38, 43, 47, 49, 99, 91]
[1, 9, 37, 40, 45, 47, 50, 100, 91]

TA貢獻1833條經驗 獲得超4個贊
我認為這樣的事情應該有效
def gradingStudents(grades):
output =[]
for g in filter(lambda x: x>38, grades):
step = g + (5 - g % 5)
output.append(step < 3 : g + step ? g)
output.extend(filter(lambda x: x<=38, grades)):
return output
# ... Your other code
print(gradingStudents(grades))

TA貢獻1875條經驗 獲得超5個贊
簡化您的方法
def finalGrade(grade, multiple_of=5, limit=38):
if not grade < limit:
grade = int(round(grade / multiple_of) * multiple_of)
return grade
grades = [20, 34, 37, 38, 39, 41, 45, 48, 52]
finalGrades = [finalGrade(grade) for grade in grades]
# [20, 34, 37, 40, 40, 40, 45, 50, 50]
- 3 回答
- 0 關注
- 134 瀏覽
添加回答
舉報