当前位置: 首页 > news >正文

python的lambda实用技巧

lambda表达式

lambda表达式是一种简化的函数表现形式,也叫匿名函数,可以存在函数名也可以不存在。

使用一行代码就可以表示一个函数:

# 格式
lambda arg[参数] : exp[表现形式]
# 无参写法
lambda : "hello"
# 一般写法
lambda a,b,c : a+b+c

1.配合map()内置函数

map():用于可迭代对象中每个元素所指定的函数,返回新的迭代器

书写格式:

# 返回参数为`list`
list = map(function[函数],iterable[可迭代对象])

使用示例:

# 普通使用
strings = ["hello","world","computer"]
demo = map(str.upper,strings)
print(list(demo))
# 配合lambda使用 切割字符串
demo2 = map(lambda x: x[2:], strings)
print(list(demo2))

在这里插入图片描述

2.配合Filter()函数使用

filter():用于筛选数组中满足条件的值,并返回一个新的可迭代对象。

语法格式:

# 返回参数为list
list = filter(function[判断函数],itrable[可迭代对象])

配合lambda函数使用示例:

number =[1,2,3,4,5,6,7]
pos = filter(lambda x :x>3,number)
print(pos)

在这里插入图片描述

3.配合reduce()函数使用

这个函数不作为function中的函数,是在functools模块中的一个函数。

reduce():具体功能是作用于对一个迭代对象的元素进行积累(累加,累乘)等操作。

语法格式:

from functools import reduce
# 返回值是一个数字
reduce(function[函数] , iterable[可迭代对象], [value][可选对象,运行函数时的初始值])

使用示例:

from functools import reduce
value = reduce(lambda x, y: x * y, [1, 2, 3, 4, 5])
print(value)

在这里插入图片描述

python装饰器

decorators高级功能,允许动态修改函数或类的行为。

接收一个函数作为参数,返回一个新的函数或修改原来的函数。

wraps:在Python的装饰器模式中,@wraps(func) 是一个来自 functools 模块的装饰器,它的作用是更新被包装函数(即被装饰的函数)的一些元数据,使其在被装饰后仍然保留原有的函数名、文档字符串、注解等属性。

语法格式:

# 这个是一个注释器
@decorators_name
# 内置装饰器
# 静态方法
@staicmethod 
@类方法
@classmethod

语法格式:

def decorat_function(orange_function):def web(*arg):befor_call_code() # 执行函数前添加result = orange_function(*arg)after_call_code() # 执行函数后添加# 使用装饰器
@decorators_function
def target_function(arg1,arg2):pass

使用示例:

def time_decorator(func):@wraps(func)def wrapper(*args, **kwargs):start_time = time.time()result = func(*args, **kwargs) #获得函数的名称,以及函数参数end_time = time.time()print(f"Function {func.__name__} executed in {end_time - start_time:.4f} seconds")return resultreturn wrapper@time_decorator#使用装饰器
def my_function():print("Hello, World!")time.sleep(1)  # 模拟一些耗时的操作
# 调用函数
my_function()

在这里插入图片描述

使用示例[带参数的接收器]:

# 将参数传递给后续使用的函数
def repeat_decorator(n):  def decorator(func):  @wraps(func)  def wrapper(*args, **kwargs):  for _ in range(n):  result = func(*args, **kwargs)  return result  return wrapper  return decorator  @repeat_decorator(3)  #使用装饰器
def say_hello():  print("Hello!")  # 调用函数  
say_hello()

在这里插入图片描述

使用示例[类装饰器]:

def add_method_decorator(cls):  # 动态地为类添加一个新方法  def new_method(self):  print("This is a new method added by the decorator.")  # 使用setattr将新方法添加到类中  setattr(cls, 'new_method', new_method.__get__(None, cls))  # 返回修改后的类  return cls  # 使用@语法应用类装饰器  
@add_method_decorator  
class MyClass:  def existing_method(self):  print("This is an existing method.")  # 创建类的实例  
obj = MyClass()  # 调用原始方法  
obj.existing_method()  # 输出: This is an existing method.  # 调用由装饰器添加的新方法  
obj.new_method()       # 输出: This is a new method added by the decorator.

在这里插入图片描述

http://www.lryc.cn/news/472678.html

相关文章:

  • VB中的资源文件(Resource File)及其用途
  • 【vue】11.Vue 3生命周期钩子在实践中的具体应用
  • 1.5 新特性 C++面试常见问题
  • [mysql]子查询的概述和分类及单行子查询
  • SpringMVC执行流程(视图阶段JSP、前后端分离阶段)、面试题
  • 宠物空气净化器有用吗?有哪几款吸毛效果好且低噪的推荐
  • linux -磁盘管理命令
  • [Chrome插件开发]关于报错Service worker registration failed. Status code: 15
  • uniapp封装movable-area+movable-view组件,实现悬浮按钮可拖动,自动吸附边缘效果,自动向两边靠拢
  • 音频重采样(libresample)
  • 使用Python来下一场雪
  • Pyspark中pyspark.sql.functions常用方法(4)
  • Nginx 配置基于IP 地址的 Web 服务器
  • 【TVM 教程】线性和递归核
  • 猫主福利大放送,双11猫奴们的购物狂欢节 养猫必备清单
  • Linux中gcc的使用
  • React 组件 API
  • 一个使用接口模式、工厂模式、模板方法模式的日志文件系统
  • openjdk17 C++源码是怎么给java字段赋值的
  • C++初阶(八)--内存管理
  • C# 企业微信机器人推送消息 windows服务应用程序的使用
  • 社区交流系统设计与实现
  • 【模型学习之路】手写+分析bert
  • Redis学习文档(常见面试题)
  • 【C++刷题】力扣-#594-最长和谐子序列
  • MoveIt 控制自己的真实机械臂【2】——编写 action server 端代码
  • C#制作学生管理系统
  • python Pandas合并(单元格、sheet、excel )
  • OJ在线编程常见输入输出练习【JavaScript】
  • 新能源汽车空调系统:绿色出行的舒适保障