脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python匿名函数及应用示例

Python匿名函数及应用示例

2021-06-14 00:25xuezhangjun Python

这篇文章主要介绍了Python匿名函数及应用,结合实例形式分析了Python匿名函数的功能、定义及函数作为参数传递的相关应用操作技巧,需要的朋友可以参考下

本文实例讲述了python匿名函数及应用。分享给大家供大家参考,具体如下:

lambda关键词能创建?型匿名函数。这种函数得名于省略了def声明函数的标准步骤。

代码如下:

?
1
2
3
4
5
#定义lambda函数
sum = lambda arg1,arg2:arg1+arg2
#调用函数
totle = sum(3,5)
print ('totle = %d'%totle)

运行如下

totle = 8

lambda函数能接收任何数量的参数但只能返回一个表达式的值

匿名函数不能直接调用print,因为lambda需要一个表达式.

应用场景:函数作为参数传递

1. 自定义函数

?
1
2
3
4
5
6
7
#定义函数
def myfunc(num1,num2,option):
  print('num1 = %d'%num1)
  print('num2 = %d'%num2)
  print('num1 + num2 = %d'%option(num1,num2))
#调用函数
myfunc(3,5,lambda x,y:x+y)

运行如下:

num1 = 3
num2 = 5
num1 + num2 = 8

2. 作为内置函数的参数

?
1
2
3
4
5
6
7
8
9
10
11
#coding=utf-8
#定义一个列表,列表中的元素是字典
stus = [{'name':'xiaoming','age':18},
    {'name':'xiaohong','age':19},
    {'name':'xiaoxue','age':17}]
#实现列表中的元素按name排序
stus.sort(key = lambda x:x['name'])
print('列表中的元素按name排序:', stus)
#实现列表中的元素按age排序
stus.sort(key = lambda x:x['age'])
print('列表中的元素按age排序:', stus)

运行结果如下:

列表中的元素按name排序:
[{'name': 'xiaohong', 'age': 19},
{'name': 'xiaoming', 'age': 18},
{'name': 'xiaoxue', 'age': 17}]
列表中的元素按age排序:
[{'name': 'xiaoxue', 'age': 17},
{'name': 'xiaoming', 'age': 18},
{'name': 'xiaohong', 'age': 19}]

希望本文所述对大家python程序设计有所帮助。

原文链接:https://blog.csdn.net/xuezhangjun0121/article/details/76945344

延伸 · 阅读

精彩推荐