I have a list T1
. I want to increase all elements of T1
by 1
except the first element. How do I do so?
T1=[0,1,2,3,4,5,6,7]
T2=[i 1 for i in T1]
The current output is
T2= [1, 2, 3, 4, 5, 6, 7, 8]
The expected output is
T2= [0, 2, 3, 4, 5, 6, 7, 8]
CodePudding user response:
Use slicing!
T1 = [0,1,2,3,4,5,6,7]
T2 = [T1[0]] [i 1 for i in T1[1:]]
Or, with enumerate
:
T1 = [0,1,2,3,4,5,6,7]
T2 = [x (i>0) for i, x in enumerate(T1)]
Output:
[0, 2, 3, 4, 5, 6, 7, 8]
CodePudding user response:
You could separate the first element from the rest and increment the rest by 1 -
first, *rest = t1
t2 = [first] [(i 1) for i in rest]
Or you could enumerate
your list and use the index -
t2 = [(val 1) if idx > 0 else val for (idx, val) in enumerate(t1)]
CodePudding user response:
The correct answer would be to slice the T1 list in two, the part that you don't want to modify and the part that you do. Just combine them afterwards:
T1=[0,1,2,3,4,5,6,7]
T2= T1[0:1] [i 1 for i in T1[1:]]
CodePudding user response:
There are several methods, 2 of them
T2 = [T1[0]] [ j 1 for j in T1[1:]]
a longer but funnier one
T2 = [x y for x,y in zip(T1, [0] [1]*(len(T1)-1))]
or just a for loop with index, so you can decide which index to operate in
T2 = list()
for i,el in enumerate(T1):
if i == 0:
T2.append(el)
else:
T2.append(el 1)
Have fun
CodePudding user response:
I've tried this:
given:
t1 = [0, 1, 2, 3, 4]
the t2
list may be calculated as following:
t2 = t1[0:1] [v 1 for i, v in enumerate(t1) if i != 0]
The first part of the list concatenation is a list: in fact if you try t1[0]
you get a TypeError
due to the fact that is impossible to concatenate int
with list
.
CodePudding user response:
I would do it like this:
for i in range(1,len(T1)):
T1[i]=T1[i] 1
This would not create a new list, but would change the values in the current list
CodePudding user response:
Relatively simple answer where you use if else condition.
T1=[0,1,2,3,4,5,6,7]
T2 = [x 1 if i>0 else x for i, x in enumerate(T1)]
# Output:
[0, 2, 3, 4, 5, 6, 7, 8]