将列表与外部浮子乘以循环
我有一个清单,包括工人的工资 我想给他们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
第一批工资是正确的,但是随后它开始给出我不想要的结果。像指数的工资[1]应该是150个以前的和225个新....
我弄错了,请协助
I have a list comprising wages for workers
I want to give them a 50% raise so i want to multiply the list by 1.5
This is my code:
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])
However this is the result i get:
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
The first wage is correct but then it starts giving results i do not want. Like wage for index[1] should be 150 previous and 225 new....etc
where am i getting it wrong please assist
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在循环的每一个迭代中,您将整个列表乘以1.5。您也可以将其更改为仅在您要迭代的索引处乘以。
或使用列表理解一次。
带有列表理解的语句乘以
Wages
列表中的所有按1.5分配给new_wages
。new_wages
IS[150.0,225.0,270.0,375.0,600.0]
分配后。编辑:
根据@Mad物理学家的评论,您应该避免将硬编码数字纳入您的代码中。因此,与其在
range
函数中具有5个,不如使用len()
,因此在您从列表中添加或删除数字后起作用。You are multiplying the entire list by a factor of 1.5 in every iteration of the loop. You can either, change it to only multiply the item at the index you are iterating.
Or using the list comprehension once.
The statement with list comprehension multiplies all items in the
wages
list by 1.5, and assigns it tonew_wages
.new_wages
is[150.0, 225.0, 270.0, 375.0, 600.0]
after the assignment.Edit:
As per a comment by @Mad Physicist, you should avoid hardcoding numbers into your code. So instead of having 5 in your
range
function, uselen()
so it works after you add or remove numbers from the list.