是否可以将for循环中的值放入列表中?

2024-04-30 03:06:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图制作一个程序,用已知的密钥矩阵破解希尔密码,当我输入密文,并将字母转换成数字时,我使用这个for循环:

letters = 'abcdefghijklmnopqrstuvwxyz'

ciphertext = input('Enter your ciphertext')
ciphertext = list(ciphertext.lower())

for symbol in ciphertext:
        num = int(letters.find(symbol))
        print(num)

我想知道是否有一种方法可以把打印出来的数字转换成一个数组,我用这个数组来表示希尔密码中涉及的矩阵,因为我需要把每一个2个字母的块插入一个2x1矩阵中,以便对每个字母执行矩阵乘法,从而得到明文。你知道吗

基本上,我试图以最有效的方式将for循环中的数字放入数组,但是我对python的编码非常陌生,所以我不知道该怎么做。你知道吗

另外,在python中是否有一种更简单的方法来使用矩阵,而我不知道这种方法会使整个事情变得更简单?你知道吗


Tags: 方法程序密码for字母密钥矩阵数字
3条回答

这里有一个方法让他们进入一个列表。你知道吗

letters = 'abcdefghijklmnopqrstuvwxyz'
ciphertext = input('Enter your ciphertext')
ciphertext = list(ciphertext.lower())
desiredArray = list(map(lambda x: int(letters.find(x)), ciphertext))

这将查找和转换为整数定义为“lambda”函数;“map”函数将lambda函数映射到密文的元素,“list”函数将结果转换为列表。这些都是值得学习的python片段。你知道吗

是的,您应该使用列表理解:

letters = 'abcdefghijklmnopqrstuvwxyz'
ciphertext = input().lower()

indices = [letters.find(c) for c in ciphertext]

这会将letters.find(c)附加到ciphertext中每个字母(这里称为c)的索引中。你知道吗

但是如果letters始终是字母表(根据维基百科的说法似乎是这样的),你可以通过使用ord来加快速度,它会给你每个字母的ASCII索引。要使'a'成为0,只需减去ord('a')

ciphertext = input().lower()
indices = [ord(c) - ord('a') for c in ciphertext]

看看维基百科上的希尔密码,你所描述的似乎并不是你所需要的。你知道吗

我的理解是你的钥匙必须是一个完美的正方形长度(n^2)。然后将键塑造成nn矩阵,并将其乘以n纯文本块。你应该调查一下numpy。它有很多处理矩阵的工具,我很确定你可以用几行字来表达这个密码:

import numpy as np

ciphertext = np.array(map(ord, input().lowercase())) - ord('a')
n = int(sqrt(len(ciphertext)))
assert n**2 == len(ciphertext), 'ciphertext must be perfect square in length'

ciphertext.reshape((n, n))  # Make ciphertext a nxn matrix
# Matrix multiply plaintext chunks of n by ciphertext
plaintext.reshape((n, -1)) @ ciphertext

似乎密文必须是可逆的。numpyallows you to check that the ciphertext is invertible (and compute its inverse)无需自己编写linalg代码。你知道吗

看起来您想在列表中返回字符的ASCII值。你可以用一个列表在线性时间内完成。你知道吗

symbols = 'axy12c'

lst = [ord(c) - ord('a') if c.isalpha() and c.islower() else -1 for c in symbols]

print(lst)
[0, 23, 24, -1, -1, 2]

既然你提到了数组,也有一种很简单的方法。你知道吗

arr = np.array(list(symbols), dtype='|S1').view(np.int8) - 97
arr[(0 > arr) | (25 < arr)] = -1

print(arr)
array([ 0, 23, 24, -1, -1,  2], dtype=int8)

相关问题 更多 >