Python 如何将成对数组列表转换为2x1数组?
我试图用Python编写一个Hill密码程序,允许用户输入自己的2x2矩阵和要编码或解码的消息。 消息“Hello World”已加密到以下列表中:Python 如何将成对数组列表转换为2x1数组?,python,arrays,encryption,Python,Arrays,Encryption,我试图用Python编写一个Hill密码程序,允许用户输入自己的2x2矩阵和要编码或解码的消息。 消息“Hello World”已加密到以下列表中: Num_Msg= [array([-24, 5]), array([12, 12]), array([ 15, -64]), array([-9, 15]), array([18, 12]), array([ 4, -64])] 现在我想把这些数组中的每一个都转换成2x1向量,以便通过2x2矩阵键得到np.dot。编码 for i in N
Num_Msg= [array([-24, 5]), array([12, 12]), array([ 15, -64]), array([-9, 15]), array([18, 12]), array([ 4, -64])]
现在我想把这些数组中的每一个都转换成2x1向量,以便通过2x2矩阵键得到np.dot。编码
for i in Num_Msg:
Vector=[np.ndarray(Num_Msg[i],shape=(2,1))]
Dot_Product=np.dot(Vector,Key_Matrix)
导致
TypeError:只有包含一个元素的整数数组才能转换为
索引
我也尝试过类似的
np.reformate(Num_Msg,(2,1))
以获得类似的结果。对这个项目的任何帮助都将是巨大的您看到的问题是,i
已经是您的矢量。所以你要寻找的循环是
for Vector in Num_Msg: # Notice Vector is the variable we're iterating over
Dot_Product=np.dot(Vector, Key_Matrix)
把一切都清理干净之后,你最终会
Num_Msg = np.array([[-24, 5], [12, 12], [15, -64], [-9, 15], [18, 12], [4, -64]])
Key_Matrix = numpy.random.rand(2, 2)
Dot_Product = numpy.array([np.dot(V, Key_Matrix) for V in Num_Msg])
但是,不需要for循环,但您可以让numpy.einsum
为您执行循环:
Dot_Product2 = numpy.einsum('fi,ij->fj', Num_Msg, Key_Matrix)
为了确保这两种方法能产生相同的结果:
numpy.allclose(Dot_Product, Dot_Product2) # True
Num_Msg:中i的第一个
i
是数组([-24,5])
i
不是索引,它是我看到的实际元素,我如何使它成为索引?我应该提到的是,我对编码的了解非常少。谢谢你,因为范围内的i(len(Num_Msg))
被认为是粗糙的,有枚举
,但“pythonic”只是对返回的elment进行操作,不需要为范围内的i(len(Num_Msg)):Msg_Vectors=np.重塑(Num_Msg[i],(2,1))消息ValueError中的结果:新数组的总大小必须为unchanged@DanielArevalo如果答案完全回答了您的问题,请不要忘记在答案左侧打上“所有重要的接受V”标记。我的帖子旁边的复选标记将其标记为有效答案。