gpt4 book ai didi

python - Python 中 STRINGS 的 switch-case 语句

转载 作者:太空宇宙 更新时间:2023-11-04 08:32:22 27 4
gpt4 key购买 nike

我需要做一些类似于 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com