I have a list that contains a few elements and I want to subtract 1 from only the first 3 elements from the list. I can't figure out what the correct code is to fulfill this task. I would appreciate it if someone could help me. Thank You!
thelist = [5,4,3,2,1]
I want it to become
[4,3,2,2,1]
One possible solution:
thelist = [5,4,3,2,1]
thelist = [v - 1 if i < 3 else v for i, v in enumerate(thelist)]
print(thelist)
Prints:
[4, 3, 2, 2, 1]
OR:
print(list(map(lambda k: k-1, thelist[:3])) + thelist[3:])
OR:
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]
You can modify the original list using a list comprehension as follows:
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]
just another solution if you wanna try it you can use numpy
import numpy as np
thelist = [5,4,3,2,1]
newnp = np.array(thelist)
newnp[0:3] -= 1
print(list(newnp))
You can use a combination of list comprehensions and array slicing
Array Slicing
First we need to split the array into 2 components, the first 3 elements: first_three =x[:3]
and the remainder remainder = x[3:]
List Comprehension
We can now subtract 1 from each of the items in first_three
and save the result in a new array one_subtracted = [num - 1 for num in first_three]
Final
We can then create the result by adding the arrays back together result = one_subtracted + remainder
Shorthand
You can also do this as part of a single expression
the_list = [5,4,3,2,1]
result = [num - 1 for num in the_list[:3]] + the_list[3:]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.