[英]How to increase the value of each item/element in a list?
我目前正在尝试制作一个Caesar解码器,因此我试图找出如何获取用户对shift值的输入,并使用该输入对列表中的每个项目进行移位。 但是每次我尝试时,都会不断给我一个错误。
例如:
ASCII中的word
为:
[119, 111, 114, 100]
如果给定的shift输入为2
,我希望列表为:
[121, 113, 116, 102]
请帮忙。 这是我第一次编程,这个Caesar解码器让我发疯:(
这就是我到目前为止
import string
def main():
inString = raw_input("Please enter the word to be "
"translated: ")
key = raw_input("What is the key value or the shift? ")
toConv = [ord(i) for i in inString] # now want to shift it by key value
#toConv = [x+key for x in toConv] # this is not working, error gives 'cannot add int and str
print "This is toConv", toConv
另外,如果你们不使用任何高级功能,那将很有帮助。 相反,请使用现有代码。 我是新手。
raw_input
返回一个字符串对象,而ord
返回一个整数。 此外,如错误消息所述,您不能将字符串和整数与+
一起添加:
>>> 'a' + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>>
但是,这正是您要在此处执行的操作:
toConv = [x+key for x in toConv]
在上面的代码中, x
将是一个整数(因为toConv
是一个整数列表),而key
将是一个字符串(因为您使用raw_input
获取其值)。
您可以通过简单地将输入转换为整数来解决问题:
key = int(raw_input("What is the key value or the shift? "))
之后,您的列表理解将按预期工作。
下面是一个演示:
>>> def main():
... inString = raw_input("Please enter the word to be "
... "translated: ")
... # Make the input an integer
... key = int(raw_input("What is the key value or the shift? "))
... toConv = [ord(i) for i in inString]
... toConv = [x+key for x in toConv]
... print "This is toConv", toConv
...
>>> main()
Please enter the word to be translated: word
What is the key value or the shift? 2
This is toConv [121, 113, 116, 102]
>>>
如果您对一种班轮感兴趣:
shifted_word = "".join([chr(ord(letter)+shift_value) for letter in word])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.