【问题标题】:How to translate using a dictionary?如何用字典翻译?
【发布时间】:2022-11-30 09:22:52
【问题描述】:

此函数采用输入 d 和一串字符 s。然后根据d,它返回从英语到 Drench 的翻译,反之亦然。如果 s 不在英语或法语词典中,则返回 Unknown。我能够做到这一点,只是,每当我运行它时,它都会返回:

dict(d, 'bonjour')
hello
Unknown
Unknown
Unknown

它返回hello,然后是Unknown。为什么?它应该只返回hello。帮助将不胜感激!

谢谢,

def dict(d, s):
    s = s.lower()

    for e, f in d.items():
        if s == e:
            print(f) 
        elif s == f:
            print(e)
        else:
            print('Unknown')
            
d = { 
    "hello": "bonjour",
    "Goodbye": "aurevoir",
    "eat": "mange",
    "world": "monde"
}

【问题讨论】:

  • if s == e or s == f,需要退出for循环(不用再比较),只有for循环完全迭代后,才能打印unknown(已经全部试过了是吧?),try以这种方式改进您的代码?
  • 您正在隐藏内置类 dict()
  • @accdias 我如何取消它的阴影?
  • 为您的函数使用另一个名称。
  • @accdias 你到底是什么意思???指定 !!!

标签: python


【解决方案1】:
def dict(d,s):

    s = s.lower()

    for e,f in d.items():
        if s == e:
            print (f) 
            break
        elif s == f:
            print (e)
            break
        else:
            print ('Unknown')

            
d = {"hello":"bonjour","Goodbye":"aurevoir","eat":"mange","world":"monde"}
dict(d,'bonjour')
>>>
hello

【讨论】:

  • 我能做到,但是有字典吗?
  • 我刚刚编辑了它。添加两行break后,Unknown就不会出现了
猜你喜欢
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多