我需要做一些类似于 CASE WHEN .. OR .. THEN 从 python 中的 SQL 获取字符串的操作。例如,如果我说“狗”或“猫”..我的翻译是“动物”。
我不想使用 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
它有效,但看起来很丑..
还有其他解决方案吗?
谢谢!
最佳答案
为了您的目的,我建议您改用由动物名称索引的字典。代码中的列表 l
也将是多余的,因为它只是此字典的键。
d = {
'cat': 'animal',
'dog': 'animal',
'turtle': 'animal'
}
word = 'cat'
print(d.get(word, word))
关于python - Python 中 STRINGS 的 switch-case 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51896284/