如何使用列表理解在具有多个条目的二维矩阵中进行切片



我试图让I在0到20的范围内。我尝试过for循环,但由于运行时间的原因,我删除了它。如何理解列表?

finallinearsystem = [
[np.transpose(i), np.transpose(pts_3d[i]) , np.dot(-y[i],np.transpose(pts_3d[i]))],
[np.transpose(pts_3d[i]), np.transpose(i) , np.dot(-x[i],np.transpose(pts_3d[i]))],]

我知道你已经接受了我的答案,但我认为你的性能问题不是因为for循环,而是因为你要多次进行几次昂贵的计算。

我会试试这个:

final_linear_system = []
for i in range(20)
transposed_i = np.transpose(i) # you're doing this twice
transposed_pts_3d_i = np.transpose(pts_3d[i]) # you were doing this 4 times

final_linear_system.append([transposed_i, transposed_pts_3d_i, np.dot(-y[i],transposed_pts_3d_i)])
final_linear_system.append([transposed_i, transposed_pts_3d_i, np.dot(-x[i],transposed_pts_3d_i)])

看起来你想为i的每个值向数组中添加两个元素,这可以用嵌套的理解来完成

print([j for i in range(5) for j in ([f"{i}a",f"{i}a"],[f"{i}b",f"{i}b"])])
# [['0a', '0a'], ['0b', '0b'], ['1a', '1a'], ['1b', '1b'], ['2a', '2a'], ['2b', '2b'], ['3a', '3a'], ['3b', '3b'], ['4a', '4a'], ['4b', '4b']]

或:


finallinearsystem = [
j for i in range(20)
for j in (
[np.transpose(i), np.transpose(pts_3d[i]) , np.dot(-y[i],np.transpose(pts_3d[i]))],
[np.transpose(pts_3d[i]), np.transpose(i) , np.dot(-x[i],np.transpose(pts_3d[i]))]
)
]

最新更新