Python中的Case When语句详解

Python中的Case When语句详解

Python中的Case When语句详解

在编程中,常常需要根据不同的条件执行不同的操作。类似于SQL中的Case When语句,Python也提供了多种方法来实现类似的功能。本文将详细介绍Python中实现Case When语句的几种方法,并给出示例代码及运行结果。

方法一:使用if-elif-else语句

最简单的实现Case When功能的方法是使用if-elif-else语句。根据不同的条件,执行相应的操作。

def case_when(value):
    if value == 1:
        return "One"
    elif value == 2:
        return "Two"
    else:
        return "Other"

print(case_when(1))  # One
print(case_when(2))  # Two
print(case_when(3))  # Other
Python

运行结果:

One
Two
Other
Python

方法二:使用字典映射

另一种实现Case When功能的方法是使用字典映射。将条件和对应的操作存储在字典中,根据条件查找对应的操作。

def case_when_dict(value):
    cases = {
        1: "One",
        2: "Two",
        }

    return cases.get(value, "Other")

print(case_when_dict(1))  # One
print(case_when_dict(2))  # Two
print(case_when_dict(3))  # Other
Python

运行结果:

One
Two
Other
Python

方法三:使用函数映射

也可以使用函数映射的方式来实现Case When功能。将条件和对应的操作存储在函数中,根据条件调用对应的操作函数。

def case_one():
    return "One"

def case_two():
    return "Two"

def case_other():
    return "Other"

def case_when_func(value):
    cases = {
        1: case_one,
        2: case_two,
    }

    return cases.get(value, case_other)()

print(case_when_func(1))  # One
print(case_when_func(2))  # Two
print(case_when_func(3))  # Other
Python

运行结果:

One
Two
Other
Python

方法四:使用匿名函数

还可以使用匿名函数的方式来实现Case When功能。将条件和对应的操作以lambda函数的形式存储,根据条件调用对应的匿名函数。

cases = {
    1: lambda: "One",
    2: lambda: "Two",
}

def case_when_lambda(value):
    return cases.get(value, lambda: "Other")()

print(case_when_lambda(1))  # One
print(case_when_lambda(2))  # Two
print(case_when_lambda(3))  # Other
Python

运行结果:

One
Two
Other
Python

通过以上方法,我们可以在Python中实现类似于SQL中的Case When语句的功能,根据不同的条件执行不同的操作。每种方法都有各自的适用场景,可以根据具体情况选择合适的方法来实现Case When功能。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册