【发布时间】:2018-06-21 22:59:40
【问题描述】:
问题是在 for 循环中很难将输入用作字典的键,我尝试使用 tuple 和 list ,但结果相同
代码如下:
import re
morse = {
"A" : ".-",
"B" : "-...",
"C" : "-.-.",
"D" : "-..",
"E" : ".",
"F" : "..-.",
"G" : "--.",
"H" : "....",
"I" : "..",
"J" : ".---",
"K" : "-.-",
"L" : ".-..",
"M" : "--",
"N" : "-.",
"O" : "---",
"P" : ".--.",
"Q" : "--.-",
"R" : ".-.",
"S" : "...",
"T" : "-",
"U" : "..-",
"V" : "...-",
"W" : ".--",
"X" : "-..-",
"Y" : "-.--",
"Z" : "--..",
"0" : "-----",
"1" : ".----",
"2" : "..---",
"3" : "...--",
"4" : "....-",
"5" : ".....",
"6" : "-....",
"7" : "--...",
"8" : "---..",
"9" : "----.",
"." : ".-.-.-",
"," : "--..--",
" " : " "
}
print("""
MORSECODE ENCYPTER """)
print("Enter the text to convert(keep in mind that upper case character, numbers , (.) and (,) are only allowed) :",end = '')
to_encrypt = input()
tuple1 = tuple( re.findall("." , to_encrypt) )
print (tuple1)
for i in tuple1 :
print(morse[tuple1])
当我输入 to_encrypt 输入(例如 H)时,它给了我:
Traceback (most recent call last):
File "x.py", line 50, in <module>
print(morse[tuple1])
KeyError: ('H',)
【问题讨论】:
-
你为什么要使用
re?您正在使用整个tuple1,morse[i]应该可以工作。但是一个简单的字典查找就可以了,for i in to_encrypt: print(morse[i]) -
我想你想要:
for i in tuple1: print(morse[i])。如果要将整个可迭代对象传递给dict,为什么要循环一个可迭代对象(这无论如何都行不通,因为您的键是单个字符)? -
感谢您修复 to_encode 的问题,我尝试制作它,但它给了我 Traceback(最近一次调用最后一次):文件“x.py”,第 50 行,在
print(morse[ to_encrypt]) KeyError: 'HH' -
您将整个值传递给 dict 查找 - 使用迭代可迭代的变量 - 即
i-morse[i]! -
感谢 AChampion,这就是问题所在
标签: python-3.x list dictionary for-loop