python - Python 中 STRINGS 的 switch-case 语句

标签 python dictionary switch-statement case type-synonyms

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

相关文章:

c# - 使用 Enumerable.Union 方法合并 Dictionary<TKey, TValue>

c++ - map::erase:按键删除和迭代器删除之间的区别?

c++ - 插入新键时会更改现有键值的地址吗?

java - 如何将字母数字电话号码转换为数字

python - 根据特定单元格中的值移动 pd.dataframe 的行

python - 导入 cv2 : ImportError: DLL load failed: windows 7 Anaconda 4. 3.0(64 位)Python 3.6.0

video - 将网站背景视频切换为图像

c - 回到默认的 switch (getch()) 开头? (C)

python - 按组别划分的百分比

python - 具有不同内核的拉普拉斯算子