python - 如何检查一个值是否存在于列表中,并将包含它的元素存储在变量中
问题描述
我正在尝试制作一个加密器,它将字母移动 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))
输出:
defghijklmnopqrstuvwxyabc
推荐阅读
- javascript - 如何组合这些功能而不重复?
- jquery - 如何使用 jquery 删除特定选择选项的旧输入?
- c - 如何将 Accelerate Framework 链接到 MacOs 中的 ac 程序?
- python - 有人可以用外行的话解释这个 python 正则表达式 ^1?$|^(11+?)\1+$
- xaml - XAML 绑定在发布模式下不工作,但在调试模式下工作
- spring-batch - 在 Spring Batch 的 SkipPolicy 中访问作业文件名参数
- rust - 实现 TryFrom 特征时的类型错误
- image-processing - 定义图像背景的好坏
- c# - 你如何键盘专注于特定项目?
- prolog - 优化 Prolog 规则