[英]How to subtract numbers from only a few elements in a list?
我有一个包含几个元素的列表,我只想从列表中的前 3 个元素中减去 1。 我无法弄清楚完成这项任务的正确代码是什么。 如果有人可以帮助我,我将不胜感激。 谢谢你!
thelist = [5,4,3,2,1]
我想让它变成
[4,3,2,2,1]
一种可能的解决方案:
thelist = [5,4,3,2,1]
thelist = [v - 1 if i < 3 else v for i, v in enumerate(thelist)]
print(thelist)
印刷:
[4, 3, 2, 2, 1]
或者:
print(list(map(lambda k: k-1, thelist[:3])) + thelist[3:])
或者:
print([v - (i<3) for i, v in enumerate(thelist)])
In [95]: thelist = [5,4,3,2,1]
In [96]: [i-1 for i in thelist[:3]] + thelist[3:]
Out[96]: [4, 3, 2, 2, 1]
您可以使用列表推导式修改原始列表,如下所示:
n = 3 # Number of first elements to modify.
modification_amount = -1
thelist[:n] = [val + modification_amount for val in thelist[:n]]
>>> thelist
[4, 3, 2, 2, 1]
>>> thelist = [5,4,3,2,1]
>>> newlist=[x-1 if thelist.index(x) < 3 else x for x in thelist]
>>> newlist
[4, 3, 2, 2, 1]
只是另一种解决方案,如果您想尝试,可以使用 numpy
import numpy as np
thelist = [5,4,3,2,1]
newnp = np.array(thelist)
newnp[0:3] -= 1
print(list(newnp))
数组切片
首先,我们需要将数组拆分为 2 个组件,前 3 个元素: first_three =x[:3]
和剩余的remainder = x[3:]
列表理解
我们现在可以从first_three
每个项目中减去 1,并将结果保存在一个新数组中one_subtracted = [num - 1 for num in first_three]
最终的
然后我们可以通过将数组加在一起来创建结果result = one_subtracted + remainder
速记
您也可以将其作为单个表达式的一部分执行
the_list = [5,4,3,2,1]
result = [num - 1 for num in the_list[:3]] + the_list[3:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.