Gon*_* AB 5 python dictionary case switch-statement type-synonyms
我需要做一些类似于 CASE WHEN .. OR .. THEN 从 Python 中的 SQL for STRINGS 的事情。例如,如果我说“狗”或“猫”……我的翻译是“动物”。
我不想使用 IF ELIF ELIF ..
我能看到的唯一解决方案是:
l = ['cat','dog', 'turttle']
d = {'animal': ['cat','dog', 'turttle']}
word = 'cat'
if word in l:
for i, j in d.iteritems():
if word in j:
print i
else:
print word
animal
Run Code Online (Sandbox Code Playgroud)
它有效,但看起来很丑陋..
还有其他解决办法吗?
谢谢!
为了您的目的,我建议您使用以动物名称为索引的字典。l您的代码中的列表也将是多余的,因为它只是此 dict 的键。
d = {
'cat': 'animal',
'dog': 'animal',
'turtle': 'animal'
}
word = 'cat'
print(d.get(word, word))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16254 次 |
| 最近记录: |