我有一份清单
angles_rad = [[0.873,0.874,0.875...],[0.831,0.832, ...],...]
我想创建一个新的列表列表,其中我从前面的角度减去每个内部列表中的所有角度:
ang_velocity = [[(0.874-0.873)/2,(0.875-0.874)/2,...],[(0.832-0.831)/2, ...],...]
我该怎么做?
内部列表的长度都不同。我的尝试如下:
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)
非常感谢任何帮助。
答案 0 :(得分:2)
你快到了。您希望使用从索引1 开始的片段压缩列表。所以:
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']]
我为了清晰起见创建了一个字符串,但只是用实际表达式替换了我的字符串插值。
一般情况下,不会迭代range(len(...)))
,除非您实际需要索引。您不需要索引,需要值,因此只需直接迭代。使用for循环:
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]]
答案 1 :(得分:1)
您可以在嵌套列表解析中使用索引:
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]