首页 > 解决方案 > 如何检查一个值是否存在于列表中,并将包含它的元素存储在变量中

问题描述

我正在尝试制作一个加密器,它将字母移动 3 次(因此 A 变为 D,B 变为 E 等)然后 X 回到 A,Y 到 B,Z 到 C。我使用的是 ASCII值来转移它们。我正在尝试查看列表的任何部分是否具有 X、Y 或 Z 的 ASCII 值,如果是,则将该元素更改回 A、B 或 C 的 ASCII 值。我知道您可以检查列表中是否有值,但是我如何实际获取该值并更改它?这是我正在尝试做的事情:

def encrypt(userInput):
    #Find Ascii Value of plaintext
    asciiValue = [ord(c) for c in userInput]
    #Convert Ascii value (list) into integers
    intAscii = [int(x) for x in asciiValue]

    encryptedAscii = [n + 3 for n in intAscii]
    if '120' in encryptedAscii:
        encryptedAscii = '97'
    elif '121' in encryptedAscii:
        encryptedAscii = '98'
    elif '122' in encryptedAscii:
        encryptedAscii = '99'
    else:
        encryptedOutput = ''.join(chr(v) for v in encryptedAscii)
    return encryptedOutput

谢谢!

标签: pythonlist

解决方案


您实际上不需要x, y, z单独检查。只需使用模运算符 ( %),因此如果溢出,它将返回a, b, c

def encrypt(userInput):
    # Find Ascii Value of plaintext
    asciiValue = [ord(c) for c in userInput]
    # Convert Ascii value (list) into integers
    intAscii = [int(x) - 97 for x in asciiValue]

    encryptedAscii = [(n + 3) % 26 + 97 for n in intAscii]
    encryptedOutput = ''.join(chr(v) for v in encryptedAscii)
    return encryptedOutput

from string import ascii_lowercase
print(encrypt(ascii_lowercase))

输出:

defghijklmnopqrstuvwxyabc

推荐阅读