问题描述
这里是 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
解决方法
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 的键,也会得到一个默认值