在每次迭代中存储for循环的输出
我想把我的循环每次运行的结果保存下来……比如说,这是我的代码:
def encrypt(key):
for char in (key):
val = (ord(char)) - (96)
举个例子,如果有人在解释器里输入“lol”,我的程序会输出……
encrypt("lol")
12
15
12
在这个例子里,我需要把12、15、12这些数字存起来,以便在其他函数中使用……有人能帮忙吗?
2 个回答
2
有很多不同的方法可以做到这一点,但在Python中,最简单的方法可能就是用列表推导式,像这样:
def encrypt(key):
return [ (ord(char)-96) for char in key ]
你可以查看这个链接了解更多信息:http://docs.python.org/tutorial/datastructures.html#list-comprehensions
比如,调用encrypt('lol')
会返回一个列表[12, 15, 12]
。
3
与其把值保存在一个临时变量val里,不如把它保存到一个列表中,然后返回这个列表。
def encrypt(key):
temp = list()
for char in(key):
temp.append((ord(char))-96)
return temp