我根据答案编辑了它:
def decode(code, key):
decode = ' '
for n in code:
for t in key:
if n == '2' and t == '1':
decode = decode + 'a'
elif n == '2' and t == '2':
decode = decode + 'b'
elif n == '2' and t == '3':
decode = decode + 'c'
等等。但是现在:
keypad.decode('43556 96753!', '22333 13331!') #hello world!
这是输入
hhiii giiig!eefff dfffd!kklll jlllj!kklll jlllj!nnooo mooom!22333 13331!xx333 w333w!nnooo mooom!qqrrr prrrp!kklll jlllj!eefff dfffd!22333 13331!
和输出
怎么回事?我检查了一下代码,看看是否有打字错误,但没有。
您应该比较t
和n
,而不是code
和key
在if
语句中:
def decode(code, key):
decode = ' '
for n in key:
for t in code:
if t == '2' and n == '1':
decode = decode + 'a'
elif t == '2' and n == '2':
decode = decode + 'b'
elif t == '2' and n == '3':
decode = decode + 'c'
return decode
也许你不打算使用嵌套循环?如何:
for n, t in zip(code, key):
if n == '2' and t == '1':
...