我有两个列表列表。
x = [[992,982,...],...,[241,251,...]]
y = [[1184,1178,...],...,[274,294,...]]
我希望获得x和y之间的角度作为列表列表
angles =[[0.87,0.874,...],...,[0.5,0.52,... ]]
我的代码如下:
angles = []
for i in range(1,10):
for item1 in x[i]:
for item2 in y[i]:
angles.append(np.arctan2(item2, item1))
这给了我作为列表的角度。
angles = [0.87,0.874,...]
我希望将角度作为列表列表。任何帮助将不胜感激。
答案 0 :(得分:0)
也可能最容易为数组使用numpy。
x_arr = np.array(x)
y_arr = np.array(y)
angles_arr = np.arctan2(x_arr, y_arr)
angles = angles_arr.tolist()
答案 1 :(得分:0)
In [53]: x = [[992,982],[241,251]]
...: y = [[1184,1178],[274,294]]
...:
您的列表迭代:
In [56]: angles = []
In [57]: for i in range(2):
...: for item1 in x[i]:
...: for item2 in y[i]:
...: angles.append(math.atan2(item2,item1))
...:
In [58]: angles
Out[58]:
[0.8734055369251891,
0.870903457075653,
0.8783886606617618,
0.8758910778163088,
0.8493883488678455,
0.8841414043445257,
0.8291796919394373,
0.8641341374390786]
在一个级别上分解该列表迭代:
In [59]: angles = []
In [60]: for i in range(2):
...: alist = []
...: for item1 in x[i]:
...: for item2 in y[i]:
...: alist.append(math.atan2(item2,item1))
...: angles.append(alist)
...:
In [61]: angles
Out[61]:
[[0.8734055369251891,
0.870903457075653,
0.8783886606617618,
0.8758910778163088],
[0.8493883488678455,
0.8841414043445257,
0.8291796919394373,
0.8641341374390786]]
我可以添加另一个级别列表追加来获得2组2组2。
数组元素配对仅产生4个值:
In [62]: X = np.array(x); Y = np.array(y)
In [63]: np.arctan2(Y,X)
Out[63]:
array([[0.87340554, 0.87589108],
[0.84938835, 0.86413414]])
我可以使用广播来获得8个值
In [65]: np.arctan2(Y[:,None,:],X[:,:,None])
Out[65]:
array([[[0.87340554, 0.87090346],
[0.87838866, 0.87589108]],
[[0.84938835, 0.8841414 ],
[0.82917969, 0.86413414]]])
请注意,这是一个3d数组(2,2,2)。
相反,我只能从循环中得到4个值:
In [66]: angles = []
In [67]: for i in range(2):
...: alist = []
...: for item1, item2 in zip(x[i],y[i]):
...: alist.append(math.atan2(item2,item1))
...: angles.append(alist)
...:
...:
In [68]: angles
Out[68]:
[[0.8734055369251891, 0.8758910778163088],
[0.8493883488678455, 0.8641341374390786]]
使用标量math.atan2
时的速度比np.arctan2
快。
或者以列表理解形式:
In [72]: [[[math.atan2(item2,item1)] for item1, item2 in zip(x[i],y[i])] for i in range(2)]
Out[72]:
[[[0.8734055369251891], [0.8758910778163088]],
[[0.8493883488678455], [0.8641341374390786]]]