使用 python 重写 if-else 语句,如 javascript 对象字面量

问题描述

这里是 javascript 中 if-else 语句的示例。

function getTranslation(rhyme) {
  if (rhyme.toLowerCase() === "apples and pears") {
    return "Stairs";
  } else if (rhyme.toLowerCase() === "hampstead heath") {
    return "Teeth";
  } else if (rhyme.toLowerCase() === "loaf of bread") {
    return "Head";
  } else if (rhyme.toLowerCase() === "pork pies") {
    return "Lies";
  } else if (rhyme.toLowerCase() === "whistle and flute") {
    return "Suit";
  }

  return "Rhyme not found";
}

更优雅的方法是使用 object 重写 if-else 实现。

function getTranslationMap(rhyme) {
  const rhymes = {
    "apples and pears": "Stairs","hampstead heath": "Teeth","loaf of bread": "Head","pork pies": "Lies","whistle and flute": "Suit",};
  
  return rhymes[rhyme.toLowerCase()] ?? "Rhyme not found";
}

可以使用 python 编写类似 javascript 对象字面量的优雅代码吗?

我使用的是 python 3.8

Javascript 代码段来自以下链接

https://betterprogramming.pub/dont-use-if-else-and-switch-in-javascript-use-object-literals-c54578566ba0

解决方法

Python 等效项:

def get_translation_map(rhyme): 
    rhymes = {
       "apples and pears": "Stairs","hampstead heath": "Teeth","loaf of bread": "Head","pork pies": "Lies","whistle and flute": "Suit"
    }
    return rhymes.get(rhyme.lower(),"Rhyme not found")

如果您不知道 dict 的内容并希望确保始终返回一个值,则另一个有用的变体:

  v = adict.get('whatever') or 'default'

即使 dict 中有一个值为 None 的键,也会得到一个默认值

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...