Multiplying some elements of a list by and constan

2019-09-03 09:42发布

I need to multiply first 3 elements of a list by a constant (say 0.3) and rest of the elements by a different constant (say 0.7).

Input: A list of unspecified length.

experience_yrs =[2.328767123287671, 2.16986301369863, 0.4931506849315068, 0.7506849315068493, 0.5780821917808219, 1.5808219178082192]

Output: A transformed list of elements being products of original element and constant.

[0.6986301369863014, 0.650958904109589, 0.14794520547945203, 0.5254794520547945, 0.4046575342465753, 1.1065753424657534]

I tried this using lambda expression.

map(lambda x: x*0.3, experience_yrs[0:3]) + map(lambda x: x*0.7, experience_yrs[3:])

Is there a better way to achieve this ?

1条回答
疯言疯语
2楼-- · 2019-09-03 09:58

Here's another way, using a list comprehension:

[ x*0.3 if i<3 else x*0.7   for i,x in enumerate(experience_yrs)  ]
查看更多
登录 后发表回答