Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python -subtraction of value within a list

I'm new to Python and I'm having difficulties with lists. I wish to subtract 1 from all the values within the list except for values 10.5. The code below gives an error that the x3 list assignment index is out of range. The code so far:

x2=[10.5, -6.36, 11.56, 19.06, -4.37, 26.56, 9.38, -33.12, -8.44, 0.31, -13.44, - 6.25, -13.44, -0.94, -0.94, 19.06, 0.31, -5.94, -13.75, -23.44, -51.68, 10.5]
x3=[]
i=0
while (i<22):
 if x2[i]==10.5:
    x3[i]=x2[i]
else:
    x3[i]=x2[i]-1
break
#The result I want to achieve is:
#x3=[10.5, -7.36, 10.56, 18.06, -5.37, 25.56, 8.38, -34.12, -9.44, -1.31, -14.44, -7.25, -14.44, -1.94, -1.94, 18.06, -1.31, -6.94, -14.75, -24.44, -52.68, 10.5]
like image 331
user1317302 Avatar asked Apr 06 '12 11:04

user1317302


2 Answers

Try the following:

x3 = [((x - 1) if x != 10.5 else x) for x in x2]
like image 161
Simeon Visser Avatar answered Oct 11 '22 09:10

Simeon Visser


x2 = [10.5, -6.36, 11.56, 19.06, -4.37, 26.56, 9.38, -33.12, -8.44, 0.31, -13.44, - 6.25, -13.44, -0.94, -0.94, 19.06, 0.31, -5.94, -13.75, -23.44, -51.68, 10.5]
x3 = map(lambda x: x if x == 10.5 else x - 1, x2)

Python being elegant.

like image 42
j13r Avatar answered Oct 11 '22 08:10

j13r