"### 3、特殊函数:\n",
" 匿名函数lambda表达式:没有函数名字的临时使用的函数,可以将lambda表达式看成是函数的简写形式。\n",
" (1)lambda表达式的语法:\n",
" lambda参数列表:表达式\n",
" (2)与函数区别:关键词不同:def、lambda;没有名称;参数列表不需要一对圆括号,只包含一个表达式,不能包含多条语句。\n",
" (3)lambda表达式的主体是一个表达式,而不是一个代码块,在表达式中可以调用其他函数,并支持默认值参数和关键字参数,表达式的结果相当于函数的返回值;"
]
},
{
"cell_type": "code",
"execution_count": 37,
"id": "927c18ae",
"metadata": {},
"outputs": [],
"source": [
"test = lambda x,y,z:x+y+z"
]
},
{
"cell_type": "code",
"execution_count": 38,
"id": "e7592970",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"130"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"test(10,20,100)"
]
},
{
"cell_type": "code",
"execution_count": 40,
"id": "4ddc9252",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"60"
]
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def test(x,y,z):\n",
" return x+y+z\n",
"test(10,20,30)"
]
},
{
"cell_type": "code",
"execution_count": 41,
"id": "cb89f972",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<function __main__.<lambda>(x=10, y=5)>"
]
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"lambda x=10,y=5:x**2+y*2"
]
},
{
"cell_type": "code",
"execution_count": 44,
"id": "af5288ed",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"110"
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x=10\n",
"y=5\n",
"x**2+y*2"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "22256d3d",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}