这是问题:
一位教授认为考试成绩有些低。教授决定 多给8% 得分不超过70的学生,或得分不超过70或5%的学生 更多 。编写一个Python程序,该程序:
我的代码:
#this code shows old scores and prints the new scores of students
position = 0 #initialize position for later
scores = [73.75, 39.45, 72.60, 45.50, 82.75, 97, 54.50, 48.00, 96.50 ]
print ("\nThese are the old scores: ", scores)
for score in scores:
if score < 70:
score *= 1.08
elif score >= 70:
score *= 1.05
scores.insert (position,float(format(score,".2f"))) #this adds the new score into position
position += 1
scores.pop (position) #this removes the old score which was pushed to +1 position
for position, score in enumerate(scores):
if score > 100:
scores[position] = 100
print ("These are the new scores:", scores)
他希望我不要使用.pop之类的东西,也不要枚举,并说有一种更简单的方法可以做到,但我只是想不到。请帮忙!
答案 0 :(得分:1)
使用range(len)
代替枚举
scores = [73.75, 39.45, 72.60, 45.50, 82.75, 97, 54.50, 48.00, 96.50 ]
print(scores)
for i in range(len(scores)):
if scores[i] < 70:
scores[i] = round(scores[i]*1.08, 2)
if scores[i] > 100:
scores[i] = 100
elif scores[i] > 70:
scores[i] = round(scores[i]*1.05, 2)
if scores[i] > 100:
scores[i] = 100
print(scores)
# [77.44, 42.61, 76.23, 49.14, 86.89, 100, 58.86, 51.84, 100]
答案 1 :(得分:0)
看看您的第二个循环:这就是您的操作方式。只需将旧值直接替换为新值即可。
for i in range(len(scores)):
if scores[i] < 70:
scores[i] *= 1.08
elif scores[i] >= 70:
scores[i] *= 1.05
没有insert
和pop
。