簡體   English   中英

如何檢查一個值是否存在於列表中,並將包含它的元素存儲在變量中

[英]How to check if a value exists in a list, and store the elements that include it in variables

我正在嘗試制作一個加密器,它將字母移動 3 次(因此 A 變為 D,B 變為 E 等)然后 X 回到 A,Y 到 B,Z 到 C。 我正在使用 ASCII 值來移動它們。 我正在嘗試查看列表的任何部分是否具有 X、Y 或 Z 的 ASCII 值,如果是,則將該元素更改回 A、B 或 C 的 ASCII 值。 我知道您可以檢查列表中是否有值,但是我如何實際獲取該值並更改它? 這是我正在嘗試做的事情:

  • 檢查 user_input 列表中是否存在 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

謝謝!

您實際上不需要分別檢查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))

Output:

defghijklmnopqrstuvwxyabc

使用ordchr很好,但還有一種更簡單的方法: str.maketransstr.translate

from string import ascii_uppercase as ABC, ascii_lowercase as abc

def encrypt(text, tr):
    return text.translate(tr)

# join translation dicts for ABCD and abcs to 
# create mapping from 2 strings of equal lenght, 
# first is "from" second is "to" mapping:  
tr = {**str.maketrans(abc, abc[3:]+abc[:3]),     # lower case a-z
      **str.maketrans(ABC, ABC[3:]+ABC[:3])}     # upper case A-Z

text = "ABCDEFGXYZabcdefgxyz"
print(text, " => ", encrypt(text,tr))

Output:

ABCDEFGXYZabcdefgxyz  =>  DEFGHIJABCdefghijabc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM