编写一个小型Python字典
我试着写一本小词典,其中第一行有一个n数字,表示词典中的单词数。接下来n行中的每一行都由两个单词组成,表示第二个单词表示第一个单词。下一行包含一个句子。一个句子由几个用空格隔开的单词组成 当用户输入Hello单词时,我试图将输出中的salam单词形象化 我可以写的代码如下:编写一个小型Python字典,python,python-3.x,Python,Python 3.x,我试着写一本小词典,其中第一行有一个n数字,表示词典中的单词数。接下来n行中的每一行都由两个单词组成,表示第二个单词表示第一个单词。下一行包含一个句子。一个句子由几个用空格隔开的单词组成 当用户输入Hello单词时,我试图将输出中的salam单词形象化 我可以写的代码如下: dic = { 'Hello': 'Salam', 'Goodbye': 'Khodafez', 'Say': 'Goftan', 'We': 'Ma'
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()
看看下面的例子,也许它能有所帮助:
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)
读取用户输入。重复多次-使用处理
KeyError
本身的get
属性从字典中获取项目:
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))
这正是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]))
问题是什么?当用户输入hello条目时,如何显示salam表达式的输出?以此类推,对于字典的所有组件,我更正了您的代码,以防您需要。尽管你可能更喜欢Austin的解决方案。当用户输入一个不在词典中的单词,而不是他在输出中输入的同一个单词时,我该怎么办?因此,基本上,如果该项不在词典中,你想输出用户输入的内容?如果用户输入的词典不在词典中,他会显示他输入的同一个单词。谢谢你带我去《时代周刊》