将列表的某些元素乘以和常数,将其他元素乘以不同的常数 [英] Multiplying some elements of a list by and constant and others by a different constant

查看:56
本文介绍了将列表的某些元素乘以和常数,将其他元素乘以不同的常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将列表的前3个元素乘以一个常数(例如0.3),并将其余元素乘以另一个常数(例如0.7).

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]

我使用lambda表达式进行了尝试.

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 ?

推荐答案

这是使用列表推导的另一种方法:

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)  ]

这篇关于将列表的某些元素乘以和常数,将其他元素乘以不同的常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆