在 for 循环中将列表与外部浮点数相乘

multiplying lists with an external float in for loop

我有一份包含工人工资的清单 我想给他们加薪 50%,所以我想将列表乘以 1.5 这是我的代码:

wages = [100, 150, 180, 250, 400]
for i in range(0,5):
    print("Previous wage for ", i, "was: ", wages[i])
    wages = [i * 1.5 for i in wages]
    print("New wage for ", i, "is", wages[i])

然而这是我得到的结果:

Previous wage for  0 was:  100
New wage for  0 is 150.0
Previous wage for  1 was:  225.0
New wage for  1 is 337.5
Previous wage for  2 was:  405.0
New wage for  2 is 607.5
Previous wage for  3 was:  843.75
New wage for  3 is 1265.625
Previous wage for  4 was:  2025.0
New wage for  4 is 3037.5

第一份工资是正确的,但后来开始给出我不想要的结果。比如 index[1] 的工资应该是之前的 150 和新的 225....等等

我哪里理解错了,请指教

您在循环的每次迭代中将整个列表乘以 1.5 倍。您也可以将其更改为仅乘以您正在迭代的索引处的项目。

wages = [100, 150, 180, 250, 400]
for i in range(len(wages)):
    print("Previous wage for ", i, "was: ", wages[i])
    wages[i] *= 1.5
    print("New wage for ", i, "is", wages[i])

或者使用一次列表理解。

wages = [100, 150, 180, 250, 400]
new_wages = [wage * 1.5 for wage in wages]
for i in range(len(wages)):
    print("Previous wage for ", i, "was: ", wages[i])
    print("New wage for ", i, "is", new_wages[i])

带有列表理解的语句将 wages 列表中的 所有 项乘以 1.5,并将其分配给 new_wagesnew_wages赋值后是[150.0, 225.0, 270.0, 375.0, 600.0]

编辑: 根据@Mad Physicist 的评论,您应该避免将数字硬编码到您的代码中。因此,不要在 range 函数中使用 5,而是使用 len(),以便在您从列表中添加或删除数字后它可以工作。