Python 3解码程序将多个数字读取为一个数字



我根据答案编辑了它:

 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!

和输出

怎么回事?我检查了一下代码,看看是否有打字错误,但没有。

您应该比较tn,而不是codekeyif语句中:

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':
    ...

最新更新