【问题标题】:Code a small Python dictionary编写一个小型 Python 字典
【发布时间】:2018-05-12 15:46:01
【问题描述】:

我试图写一个小字典,其中第一行有一个 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()

【问题讨论】:

  • 问题是什么?
  • 当用户输入 hello 条目时,如何才能显示 salam 表达式的输出?对于字典的所有组件,依此类推
  • 好吧,我更正了你的代码,以防你想要那样。即使您可能更喜欢 Austin 的解决方案。

标签: python python-3.x


【解决方案1】:

读取用户输入。重复多次 - 使用处理 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))

【讨论】:

  • 当用户输入一个不在字典中的单词,而不是他在输出中输入的同一个单词时,我该怎么办?
  • 所以基本上你想输出用户输入的内容,如果该项目不在字典中?
  • 如果用户输入的字典不在字典中,他会显示他输入的同一个词。
  • 感谢您带我度过时光
【解决方案2】:

看看下面的例子,也许会有所帮助:

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)

【讨论】:

    【解决方案3】:

    这正是 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]))
    

    【讨论】:

      猜你喜欢
      • 2021-07-13
      • 2010-10-20
      • 2014-10-02
      • 1970-01-01
      • 2012-10-17
      • 2017-08-08
      • 2015-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多