为了账号安全,请及时绑定邮箱和手机立即绑定

在不使用 .pop 的情况下替换列表中的项目?

在不使用 .pop 的情况下替换列表中的项目?

慕运维8079593 2021-07-05 18:07:47
这是问题:一位教授觉得考试成绩有点低。教授决定给70分以下的学生加8%的学分,给70分以上的学生加5%的学分。编写一个 Python 程序:将分数存储在列表中,并打印初始分数,并显示一条消息:分数 = [73.75, 39.45, 72.60, 45.50, 82.75, 97, 54.50, 48.00, 96.50 ]使用循环,处理每个分数以计算新分数并将其存储在同一个列表中。您不能更改列表的顺序,因为分数对应于班级名册。添加额外学分后,将每个新分数截断为不超过 100。打印新乐谱列表,并附上一条短消息您不能在您的程序中使用多个列表。您的程序必须处理任意长度的列表。上面的列表仅用于您的程序测试。我的代码:#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 positionfor position, score in enumerate(scores):    if score > 100:        scores[position] = 100print ("These are the new scores:", scores)他希望我不要使用 .pop 或 enumerate 之类的东西,并说有一种更简单的方法可以做到,但我想不出一个方法。请帮忙!
查看完整描述

2 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

使用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]


查看完整回答
反对 回复 2021-07-13
?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

看看你的第二个循环:你就是这样做的。只需直接用新值替换旧值即可。


for i in range(len(scores)):

    if scores[i] < 70:

        scores[i] *= 1.08

    elif scores[i] >= 70:

        scores[i] *= 1.05

没有了insert和pop。


查看完整回答
反对 回复 2021-07-13
  • 2 回答
  • 0 关注
  • 150 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信