I had to do a "gas factory" ! to change some values of my list of tuples:
I would like to transform this list:
gridDiagPosL=[[(t, t), (t, 0, 2*pi)],
[(t, -2/3*pi + t), (t, 2/3*pi, 2*pi)],
[(t, -4/3*pi + t), (t, 4/3*pi, 2*pi)],
[(t, 2/3*pi + t), (t, 0, 4/3*pi)],
[(t, 4/3*pi + t), (t, 0, 2/3*pi)]]
into this list :
gridDiagNegL=[[(t, 2*pi - t), (t, 0, 2*pi)],
[(t, 8/3*pi - t), (t, 2/3*pi, 2*pi)],
[(t, 10/3*pi - t), (t, 4/3*pi, 2*pi)],
[(t, 4/3*pi - t), (t, 0, 4/3*pi)],
[(t, 2/3*pi - t), (t, 0, 2/3*pi)]]
below my "gaz factory" :
gridDiagNegL=[]
for diag in gridDiagPosL :
diagL=[]
for tupl in diag :
diagL.append(list(tupl))
newValue=- diagL[0][1]+2*pi
#print('newValue : ',newValue)
diagL[0][1]=newValue
diagT=[]
for listElem in diagL :
diagT.append(tuple(listElem))
gridDiagNegL.append(diagT)
Is there a more elegant and above all simpler way to do it?
A simpler way of writing your function is this:
def gaz_factory(grid_list):
ret = []
for l in grid_list:
tuple_x, tuple_y = l[0], l[1]
new_value = -tuple_x[1] + 2 * pi
new_list = [(tuple_x[0], new_value), tuple_y]
ret.append(new_list)
return ret
It is not necessary to convert the tuples to lists, especially in the case of the second tuple in each list since that one is not modified. Since there's always two tuples, it's also more readable to assign them directly with indices instead of using a for loop.
Using list comprehensions we can also do it in one line:
def gaz_factory(grid_list):
return [[(lst[0][0], -lst[0][1] + 2 * pi), lst[1]] for lst in grid_list]