我试图理解这段代码中的最后一行 - 我知道它正在 encdic
中获取等效的明文字符(加密字典并将其全部连接在一起以创建加密消息。什么是l.lower
代码正在执行(获取大写字符并将其转换为小写字符?如果所有字符都已经是小写 - 我如何缩短最后一行
return s.join(encdic.get(c.lower(), c) for c in plaintext)
plaintext = "hhis is a fairly long piece of plainhexh fourscore and seven"
d = 'gikaclmnqrpoxzybdefijstuvw' #decryption key
encdic = dict(zip(alphabet, d)) #create decryption dictionary
decdic = dict(zip(d, alphabet)) #create decryption dictionary
def encrypt(plaintext, d):
s=""
return s.join(encdic.get(c.lower(), c) for c in plaintext)
当我将代码缩短为:
return s.join(encdic.get(c) for c in plaintext)
我收到以下错误
TypeError: sequence item 4: expected str instance, NoneType found
我该如何解决这个问题?
更新:
我已将代码更改为:
return s.join(encdic.get(c,c) for c in plaintext)
似乎工作没有错误,但为什么?
最佳答案
您的 key 有两次 i
且缺少 h
数据:
d = 'gikaclmnqrpoxzybdefijstuvw' # decryption key
测试代码:
print(sorted(list(set(d))))
print(sorted(list(d)))
结果:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
关于python - 需要缩短get函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42870107/