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

时间:2018-10-10 21:04:19

标签: python python-3.x

这是问题:

一位教授认为考试成绩有些低。教授决定 多给8% 得分不超过70的学生,或得分不超过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 position

for position, score in enumerate(scores):
    if score > 100:
        scores[position] = 100

print ("These are the new scores:", scores)

他希望我不要使用.pop之类的东西,也不要枚举,并说有一种更简单的方法可以做到,但我只是想不到。请帮忙!

2 个答案:

答案 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

没有insertpop