简体   繁体   English

使用带有另一个列表列表中的元素的操作创建列表列表

[英]Creating a list of lists using operations with elements from another list of lists

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. 任何帮助将不胜感激。

You are almost there. 你快到了 You want to zip the list with a slice of itself starting from index 1 . 您要使用索引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 . 通常,除非确实需要使用index否则不要在range(len(...)))进行迭代 You don't need the indices, you need the values , so just iterate over things directly. 您不需要索引,而需要 ,因此只需直接遍历事物即可。 Using for-loops: 使用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]]

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM