Python - calculating a value inside a list

I am new to Python and am having difficulty with lists. I want to subtract 1 from all the values ​​in the list, with the exception of 10.5. The code below shows an error where the destination index of list x3 is out of range. 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] 
+6
source share
5 answers

Try the following:

 x3 = [((x - 1) if x != 10.5 else x) for x in x2] 
+7
source
 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) 

Elegant Python.

+3
source
 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=[] for value in x2: if value != 10.5: value -= 1 x3.append(value) 
0
source

The built-in Python function map pretty much matches the situation you have in your hands using this, and the anonymous function that solves the problem becomes single-line:

 map(lambda x: x if x == 10.5 else x - 1, x2) 

Or, if you are not comfortable using lambda functions, you can define the function separately:

 def func(x): if x == 10.5: return x else: return x - 1 map (func, x2) 
0
source

A map is the best option, but if you want to use another use, reduce: D

 >>> 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] >>> reduce(lambda x,y: x+[y if y==10.5 else y-1], x2, []) [10.5, -7.36, 10.56, 18.06, -5.37, 25.56, 8.38, -34.12, -9.44, -0.69, -14.44, -7.25, -14.44, -1.94, -1.94, 18.06, -0.69, -6.94, -14.75, -24.44, -52.68, 10.5] 
0
source

Source: https://habr.com/ru/post/912589/


All Articles