python中的三元运算符,匿名函数lambda,高阶函数map和装饰器的使用教程

三元运算符

python中三元运算符基本结构为:
条件为真时候的返回值 if 判断条件 else 条件为假时候的返回值
举个栗子:

score = 90
res = 'good' if score>=60 else 'bad'
print(res) 
# 打印结果为good

匿名函数,lambda表达式

匿名函数,顾名思义,就是没有函数名字,但却能实现函数功能的函数。借助lambda关键字实现。注意,匿名函数除了没有函数名,调用方法跟普通函数完全一样。
res = lambda 变量名:运算逻辑

y = lambda x, y: x**2+y**2  # 输入变量为x,y。函数逻辑为x**2+y**2。用y接受返回值
res = y(3, 4)
print(res) 
# 打印结果为25

map使用

基本格式为:y = map(func, 传入func的参数列表),返回值也是一个列表。

list_x = [1, 2, 3, 4]
res = map(lambda x: x**2, list_x) # 会将list_x里面每一个值代入前面的函数运算,每个运算的结果放入列表res中
print(list(res)) # res=[1, 4, 9, 16]
list_x = [2, 3, 4, 5]
list_y = [3, 4, 5, 6]
res = map(lambda x, y: x**2+y**2, list_x, list_y) # list_x, list_y每次都各取一个值带入作为参数x,y带入前面的函数运算
print(list(res)) # res=[13, 25, 41, 61]

装饰器

在实际写程序中,我们可能会经常遇到想打印一下某个函数运行时间或者是想对一堆不同的函数执行相同操作的时候,如果我们一个函数一个函数地去书写这些相同地逻辑,会显得程序冗余,且增加工作量。这时候,我们可以用装饰器来解决这类问题。装饰器,顾名思义,就是统一给函数“装饰”,附加额外功能地工具。装饰器在设计的时候有点繁杂,但是在调用的时候很简单。借助“@”这个“语法糖”,后面跟上装饰器函数名字,把这个放在要附加额外功能的函数的上面,就能实现额外的功能。
装饰器的大体框架如下:

def decorator():
    def wrapper(*args, **kwargs):
        # 要给函数附加的额外的功能
        func(*args, **kwargs)
        # 要给函数附加的额外的功能
    return wrapper
    
@decorator
def func():
    pass

比如,我们要做一个time_cost的装饰器,记录每个函数运行的时间,依葫芦画瓢,如下:

import time

def cost_time(func):
    def wrapper(*args, **kwargs):
        begin = time.clock()
        func(*args)
        end = time.clock()
        print("cost time:", end-begin, 's')
    return wrapper

@cost_time
def func1():
    time.sleep(3)

@cost_time
def func2(name):
    print('hello! '+name)
    time.sleep(2)

func1()
func2('cheng')

运行结果如图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40438165/article/details/83089543