我目前正在使用Python 3.5,而且我的字典中的变量存在问题。我将数字1-29作为键,字母作为对,并且由于某种原因,没有双位数字注册为一个数字。例如,11将表示为1和1(F和F)而不是11(I)或13表示为1和3(F和TH)而不是13(EO)。有没有办法解决这个问题,以便我可以得到两位数的值?
我的代码在这里:
Dict = {'1':'F ', '2':'U ', '3':'TH ', '4':'O ', '5':'R ', '6':'CoK ', '7':'G ', '8':'W ', '9':'H ',
'10':'N ', '11':'I ', '12':'J ', '13':'EO ', '14':'P ', '15':'X ', '16':'SoZ ', '17':'T ',
'18':'B ', '19':'E ', '20':'M ', '21':'L ', '22':'NGING ',
'23':'OE ' , '24':'D ', '25':'A ', '26':'AE ', '27':'Y ', '28':'IAoIO ', '29':'EA '}
textIn = ' '
#I'm also not sure why this doesn't work to quit out
while textIn != 'Q':
textIn = input('Type in a sentence ("Q" to quit)\n>')
textOut = ''
for i in textIn:
if i in Dict:
textOut += Dict[i]
else:
print("Not here")
print(textOut)
答案 0 :(得分:1)
您的for i in textIn:
会循环播放输入中的各个字符。因此,如果你写11
,它实际上是一个字符串'11'
,而for i in '11'
将分别覆盖'1'
:
>>> text = input()
13
>>> text
'13' # See, it's a string with the single-quote marks around it!
>>> for i in text:
... print(i)
...
1
3
>>> # As you see, it printed them separately.
您根本不需要for
循环,只需使用:
if textIn in Dict:
textOut += Dict[textIn]
由于你的dict有密钥'11'
,而你的textIn
等于'11'
。
您的代码中还有另一个主要问题; 每个循环都会覆盖textOut
变量,因此您将丢失已完成的所有操作。您想在while
循环之外创建它:
textOut = ''
while textIn != 'Q':
textIn = input('Type in a sentence ("Q" to quit)\n>')
if textIn in Dict:
textOut += Dict[textIn]
else:
print("Not here")
print(textOut)