Reputation: 33
I have a list of lists
angles_rad = [[0.873,0.874,0.875...],[0.831,0.832, ...],...]
and I would like to create a new list of lists, where I subtract all the angles in each inner list from the angles before them:
ang_velocity = [[(0.874-0.873)/2,(0.875-0.874)/2,...],[(0.832-0.831)/2, ...],...]
How can I do this?
The lengths of the inner lists are all different. My attempt was the following:
angular_velocity = []
for i in range(374):
for j in range all:
alist = []
for angle1, angle2 in zip(orientations[i][j],orientations[i][j+1]):
alist.append((angle2 - angle1)/2)
angular_velocity.append(alist)
Any help would be greatly appreciated.
Upvotes: 0
Views: 50
Reputation: 95948
You are almost there. You want to zip the list with a slice of itself starting from index 1. So:
In [1]: angles_rad = [[0.873,0.874,0.875],[0.831,0.832]]
...: [[f"({y} - {x})/2" for x,y in zip(sub, sub[1:])] for sub in angles_rad]
...:
...:
Out[1]: [['(0.874 - 0.873)/2', '(0.875 - 0.874)/2'], ['(0.832 - 0.831)/2']]
I created a string for clarity, but just replace my string interpolation with the actual expression.
In general, do not iterate over range(len(...)))
unless you actually need the indices. You don't need the indices, you need the values, so just iterate over things directly. Using for-loops:
In [2]: final = []
In [3]: for sub in angles_rad:
...: intermediate = []
...: for x, y in zip(sub, sub[1:]):
...: intermediate.append((y - x)/2)
...: final.append(intermediate)
...:
In [4]: final
Out[4]: [[0.0005000000000000004, 0.0005000000000000004], [0.0005000000000000004]]
Upvotes: 2
Reputation: 71451
You can use indexing in a nested list comprehension:
angles_rad = [[0.873,0.874,0.875],[0.831,0.832]]
new_angles = [[(b[i+1]-b[i])/float(2) for i in range(len(b)-1)] for b in angles_rad]
Upvotes: 1