python case when函数
时间: 2024-05-10 18:13:00 浏览: 238
在 Python 中,没有内置的 case when 函数,但是可以通过 if/elif/else 语句来实现类似于 case when 的功能。if/elif/else 语句可以根据条件执行不同的代码块。例如:
```
x = 10
if x < 0:
print("x is negative")
elif x == 0:
print("x is zero")
else:
print("x is positive")
```
上面的代码中,根据变量 x 的值执行不同的代码块。如果 x 小于 0,打印“x is negative”;如果 x 等于 0,打印“x is zero”;否则,打印“x is positive”。
除了 if/elif/else 语句外,也可以使用字典(dictionary)来实现类似于 case when 的功能。字典可以将一个值映射到另一个值,例如:
```
def case_when(x):
return {
x < 0: "x is negative",
x == 0: "x is zero",
x > 0: "x is positive",
}[True]
```
上面的代码中,定义了一个名为 case_when 的函数,它接受一个参数 x,返回一个字典。字典将 x < 0 映射到字符串“x is negative”,将 x == 0 映射到字符串“x is zero”,将 x > 0 映射到字符串“x is positive”。最后,使用 [True] 取出字典中 True 对应的值。这样,根据变量 x 的值返回不同的字符串。
阅读全文
相关推荐


















