用Python实现简单对称加密

2024-09-28 23:37:52 发布

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

我想通过使用echaracters中的字符更改每个字母来加密一些字母,该字符的索引与characters中的字母相同。 因此,我尝试使用zip()来迭代这两个列表。 首先,我迭代了userInput,在同一个循环中,我迭代了key(也就是zip(characters, echaracters)) 然后我检查i是否等于a,如果条件是True,我将b添加到cipher

userInput = input("Enter: ")

characters = ["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"]

echaracters = ["@", "$", "(", "]", "=", ")", "&", "#", "!", "%", "~", "[", "/", ";", "*", "}", "9", "?", "5", "1", "_", ">", "<<", "+", ",", "-"]

key = zip(characters, echaracters)

cipher = ""

for i in userInput:
    for a, b in key:
        if i == a:
            cipher += b

print(cipher)

输出

Enter: ABC
@

我不明白为什么它只返回第一个符号
期望输出

Enter: ABC
@$(

我做错了什么


Tags: keyintrue列表for字母zip条件
3条回答

原因是因为'key'是一个zip类型,在第一次迭代后会丢失它的值,因为zip类型是一个迭代器Here是一个类似的问题。 你的代码有点复杂。有更简单的方法来完成你的任务

userInput = input("Enter: ")
characters = ["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"]
echaracters = ["@", "$", "(", "]", "=", ")", "&", "#", "!", "%", "~", "[", "/", ";", "*", "}", "9", "?", "5", "1", "_", ">", "<<", "+", ",", "-"]

cipher = ""
for i in userInput:
  cipher += echaracters[characters.index(i)]
print(cipher)
SYBMOLS = {
    "A": "@",
    "B": "$",
    "C": "(",
    "D": "]",
    "E": "=",
    "F": ")",
    "G": "&",
    "H": "#",
    "I": "!",
    "J": "%",
    "K": "~",
    "L": "[",
    "M": "/",
    "N": ";",
    "O": "*",
    "P": "}",
    "Q": "9",
    "R": "?",
    "S": "5",
    "T": "1",
    "U": "_",
    "V": ">",
    "W": "<<",
    "X": "+",
    "Y": ",",
    "Z": "-",
}

userInput = input("Enter: ")

for symbol in userInput:
    print(SYBMOLS[symbol], end="")


此外,如果您只需要列表而不需要字典,请不要:

characters = ["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"]

你可以用

from string import ascii_uppercase

print(ascii_uppercase) # example zip(ascii_uppercase, echaracters)

# ABCDEFGHIJKLMNOPQRSTUVWXYZ

您的key在第一次循环传递后变为空

您可以尝试以下方法:

key=list(zip(characters, echaracters))
for i in userInput:
    for a, b in key:        
        if i == a:            
            cipher += b

相关问题 更多 >