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

How do I use list comprehension for slicing in a 2d matrix with multiple entries?

我试图让 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]))],]

您似乎想为 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]))]
    )
]

我知道您已经接受了我的回答,但我认为您的性能问题不是因为 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)])