[英]I'm trying to figure out simple list encryption in Python
So, I have to simulate some sort of encryption protocol. 因此,我必须模拟某种加密协议。 For example, I have list Hey=['Z','A'] I then transform that list into ascii list using ord() command. 例如,我有列表Hey = ['Z','A']然后我使用ord()命令将该列表转换为ascii列表。 No big deal. 没什么大不了。 Problem is here. 问题在这里。 In order to encrypt I enter some shift value that will move the ascii value and then reform it back to a letter. 为了加密,我输入了一些移位值,该值将移动ascii值,然后将其重新构造回字母。 It's all supposed to be capital letters ranging from A to Z, so ascii code ranges from 65 to 90. I've modified shift value, so that even if it's bigger than 26 it's still works fine. 假定它们都是大写字母,范围从A到Z,所以ASCII码的范围从65到90。我已经修改了shift值,因此即使它大于26,它仍然可以正常工作。 However, how do I modify ascii list itself, so that if one element of a list is bigger than 90 it shifts back? 但是,如何修改ascii列表本身,以便如果列表中的一个元素大于90则将其移回? I've tried this: 我已经试过了:
num=[ord(i)+shift for i in hey]
if num[i]>90:
num[i]=num[i]-26
However, shift will happen only if both (or all) elements of a list are bigger than 90. Is there a way to make that condition affect each element separately? 但是,仅当列表的两个(或所有)元素都大于90时,才会发生移位。是否有办法使该条件分别影响每个元素? So that if ascii value of one element is bigger than 90 then shift will happen, but another value will be unaffected until it becomes bigger than 90. 因此,如果一个元素的ascii值大于90,则将发生移位,但另一个值直到它大于90时,才会受影响。
I think using the modulo operator %
would be better here. 我认为在这里使用模运算符%
会更好。 This gets the remainder of a division. 这得到除法的其余部分。
Examples: 例子:
>>> 10 % 5
0
>>> 10 % 2
0
>>> 10 % 3
1
>>> 10 % 6
4
Using this, you could replace your code with this: 使用此代码,您可以将代码替换为:
num = [(ord(i) + shift - 65) % 26 + 65 for i in hey]
This also works with large values of shift. 这也适用于较大的shift值。 Subtracting 26 means that you can still go out of range when shift >= 27
. 减去26意味着当shift >= 27
时,您仍然可以超出范围。
num=[(ord(i)+shift) if ord(i) + shift <= 90 else (ord(i)+shift - 26) for i in hey]
尽管我认为您的其他地方有问题...您可能应该总结一下ascii集的开始
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.