"default"条件语句的 Pythonic 方式?

标签 python python-3.x switch-statement

我有一个多层次的 if-elif-else 结构,但最后一层 else 总是相同的语句:

if statement1:
    if something:
        do_thing()
    elif something_else:
        if something_something:
            do_thing_something()
        elif somethingg:
            do_thingg()
        else:
            do_default()
    else:
        do_default()
else: 
    do_default()

如您所见,我使用了 3 次 do_default(),我觉得有更好的方法。在其他语言中,这基本上是 switch-case 语句中的 default,但 Python 没有 switch-case。我想知道是否还有其他方法可以更优雅地/“Python地”解决这个问题? Or is the only way to use dicts or implement my own switch-case

最佳答案

您可以尝试取消嵌套您的条件:

if statement1 and something:
    do_thing()
elif statement1 and something_else and something_something:
    do_thing()
elif statement1 and something_else and somethingg:
    do_thingg()
else:
    do_default()

关于 "default"条件语句的 Pythonic 方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58220004/

相关文章:

python - 如何用空格替换标签 Beautiful Soup

python - 转移到新计算机后,在虚拟环境中找不到 Flask 扩展

python - 用指数定律拟合数据

python - 在python中将不规则时间序列转换为每小时数据并具有正态分布

python - Pandas 提取和替换值

c - 关于 C 中的 switch{} 大小写?

c# - 哪个字符串比较器与 switch 语句一起使用?

python - 可移植远程连接将数据从 MySQL 提取到 Excel

python - 将元组列表转换为 Pandas 数据框的单列?

swift ->.. 作为 Swift 中的后缀