python switch语句

采用dict与true结合的方式实现

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
fun1 = lambda x: x
fun2 = lambda x: 1
fun3 = lambda x: 3-x

fun = lambda x:{
    x >= 0 and x< 1: fun1(x),
    x >= 1 and x< 2: fun2(x),
    x >= 2 and x< 3: fun3(x)
}[True]

x= np.linspace(0,3-1e-6,100)
y = list(map(fun,x))


plt.plot(x,y)
plt.show()

结果:

你可能感兴趣的:(python)