如何将列表中元素的位置更改为实际元素(关键字密码)?

时间:2016-12-30 19:23:29

标签: python list encryption keyword

此密码使用关键字并将其重复为输入的消息的长度,然后两者都转换为数字(关键字的每个字母的位置和字母列表中的消息)然后将它们添加到一起并且被支持然后是转换回字母表中的字母。

alpha =         ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
keyword = input("Please enter a keyword: ")

sentence = input("Enter message: ")

new_keyword = []
while len(keyword) < len(sentence):
    keyword = keyword + keyword
keyword = (keyword.lower())


for letters in keyword:
    pos1 = alpha.index(letters) + 1
    new_keyword.append(pos1)
print (new_keyword)

new_sentence = []   

for letters in sentence:
    pos2 = alpha.index(letters) + 1
    new_sentence.append(pos2)
print (new_sentence)

joined = [x + y for x, y in zip(new_keyword, new_sentence)]
print (joined)

这是我的代码

我需要找到一种方法将联合列表再次转换为字母,即加密消息

请帮助

1 个答案:

答案 0 :(得分:0)

到目前为止,您已将字母移动了适当的数量,但仍保留了序数(或数字)值。

问题1是处理超过26的字母(例如z(26)+ a(1)= 27)。

问题2是使用alpha数组将值转回数字。

我已将打印报表留在原处,以便您可以看到正在发生的事情。

# Original code - unedited
alpha = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
keyword = input("Please enter a keyword: ")

sentence = input("Enter message: ")

new_keyword = []
while len(keyword) < len(sentence):
    keyword = keyword + keyword
keyword = (keyword.lower())


for letters in keyword:
    pos1 = alpha.index(letters) + 1
    new_keyword.append(pos1)
print (new_keyword)

new_sentence = []   

for letters in sentence:
    pos2 = alpha.index(letters) + 1
    new_sentence.append(pos2)
print (new_sentence)

joined = [x + y for x, y in zip(new_keyword, new_sentence)]
print (joined)

# Take any value over 26 and wrap it back round (so z + 1 = a)

for i in range(len(joined)):
    if joined[i] > 26:
        joined[i] -= 26

print (joined)

# Convert each numeric value back into its character, using the alpha list

ciphertext = []

for letters in joined:
    char = alpha[letters - 1]
    ciphertext.append(char)

print(ciphertext)

更简单的方法是使用ord()和chr()函数。它们分别将字符转换为ASCII值并返回。