我试着写一个小字典,其中第一行中有一个n号,表示字典中的单词数。 n个下一行中的每一行由两个单词组成,表示第二个单词表示第一个单词。下一行包含一个句子。一个句子由几个由空格分隔的单词组成。
当用户输入Hello字样时,我尝试将输出中的单词salam可视化。
我能编写的代码是:
dic = {
'Hello': 'Salam',
'Goodbye': 'Khodafez',
'Say': 'Goftan',
'We': 'Ma',
'You': 'Shoma'
}
n = int(input())
usrinp = input()
for i in range(n):
for i in dic:
if usrinp in dic:
print(i + ' ' + dic[i])
else:
usrinp = input()
答案 0 :(得分:1)
阅读用户输入。重复这么多次 - 使用处理get
本身的KeyError
属性从字典中获取项目:
dic = {'Hello': 'Salam', 'Goodbye': 'Khodafez', 'Say': 'Goftan', 'We': 'Ma', 'You': 'Shoma'}
n = int(input())
for _ in range(n):
print(dic.get(input(), 'Wrong Input'))
修改强>:
dic = {'Hello': 'Salam', 'Goodbye': 'Khodafez', 'Say': 'Goftan', 'We': 'Ma', 'You': 'Shoma'}
n = int(input())
for _ in range(n):
usrinp = input()
print(dic.get(usrinp, usrinp))
答案 1 :(得分:0)
看一下下面的例子,也许它会有所帮助:
dic = {
'Hello': 'Salam',
'Goodbye': 'Khodafez',
'Say': 'Goftan',
'We': 'Ma',
'You': 'Shoma'
}
# Get the text, remove whitespaces and define
# it as title (to be exaclty equal to the dict)
text = input().strip().title()
# Convert the text into a list
text = text.split()
result = []
# Get the translation for each word
for t in text:
if t in dic:
result.append(dic[t])
# Join the list to print a string
print ' '.join(result)
答案 2 :(得分:0)
这正是OP代码的更正版本,不再是你所需要的:
dic = {'Hello': 'Salam', 'Goodbye': 'Khodafez', 'Say': 'Goftan', 'We': 'Ma','You': 'Shoma'}
n = int(input())
for i in range(n):
usrinp = input()
while usrinp not in dic.keys():
usrinp = input()
print(str(i) + ' ' + str(dic[usrinp]))