知识点总结:
- 函数的参数列表定义
- 定义函数时指定默认值
- 不定参数
- 参数列表带*意义(不定参数tuple)
- 参数列表带**的意义(不定参数dictionary)
- Lambda表达式
- lambda 格式
- lambda 使用
- 高级lambda工具 —— map filter
函数的参数列表定义
指定默认值
# 带有默认值的函数c=2调用函数时可无需传入该参数
def func(a, b, c=2):
print(a, b, c)
func(1,2,3)
# 输出
1 2 3
# 指定实参对应的形参
func(c=1, a=2, b=3)
# 输出
2 3 1
- Python不支持不同参数列表的方法重载,故一般用不定参数的方式加以实现。
def avg(score1, score2, score3):
return (score1 + score2 + score3)/3
def avg(score1, score2):
return (score1 + score2)/2
print(avg(32,4,100))
# 输出
Traceback (most recent call last):
File "C:/Users/Administrator/PycharmProjects/untitled/062.py", line 9, in <module>
print(avg(32, 4, 100))
TypeError: avg() takes 2 positional arguments but 3 were given
不定参数
参数列表带*意义
- 函数定义参数为带*变量,意为可传入一个或多个参数(不定参数),在函数内将其转为一个tuple的形参。
def to_tuple(*scores):
print(scores)
to_tuple(12,23,45,2)
# 输出
(12, 23, 45, 2)
若传入实参为Iterable,则需在变量名前加*传入
def avg(*scores):
print(sum(scores) / len(scores))
# scores为任意Iterable
scores = (12, 23, 34, 45)
# 传入Iterable对象前应加*以分解每个元素
avg(*scores)
# 输出
28.5
传入多个参数的情况
def avg(*scores):
print(sum(scores) / len(scores))
# 传入4个参数 而不是一个Iterable对象
avg(1,2,3,4)
# 输出
2.5
参数列表带**意义
- 函数定义参数为带**变量,意为可传入一个或多个mapping参数(不定参数),在函数内将其转为一个dictionary的形参。
def to_dictionary(**employee):
print(employee)
to_dictionary(name='tome', age=22, dept='dev')
# 输出
{'name': 'tome', 'age': 22, 'dept': 'dev'}
若传入实参为dictionary,则需在变量名前加**传入
def display(**employee):
print(employee)
d = dict(name='tome', age=22, dept='dev')
# 传入dictionary对象前应加**以分解每个mapping元素
display(**d)
# 输出
{'name': 'tome', 'age': 22, 'dept': 'dev'}
匿名函数基本格式【lambda 参数:方法体】
定义一个lambda
f = lambda x, y : print((x + y))
f(5, 2)
实现一个选择不同语言输出的demo
def hello_chinese(name):
print('你好:',name)
def hello_english(name):
print('hello:',name)
while True:
name = input('(stop退出)请输入名字:\n')
if name == 'stop':
break
language = input('请输入语言:\nc => 中文\ne => 英文\nj => 日文\n')
if language == 'c':
action = hello_chinese
elif language == 'e':
action = hello_english
elif language == 'j':
# 使用lambda实现一个分支
action = lambda name:print('こんにちは:',name)
action(name)
使用dictionary改进判断方法,将函数赋值给dict
# 将函数传递给dict
operation = {
'c': hello_chinese,
'e': hello_english,
'j': lambda name: print('こんにちは:', name)
}
while True:
name = input('(stop退出)请输入名字:\n')
if name == 'stop':
break
language = input('请输入语言:\nc => 中文\ne => 英文\nj => 日文\n')
operation.get(language, lambda name: print('Hi!{},这门外语我还不会!'.format(name)))(name)
lambda 高级工具,map/filter
map 实现l中每个数+5
l = list(range(1, 21))
res = []
# 1. 循环
for x in l:
res.append(x + 5)
# 2. 推导
res = [x+5 for x in l]
# 3. map
def add_number(x):
return x + 5
res = list(map(add_number, l))
print(res)
# 输出
[6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
filter 过滤掉奇数
l = list(range(1, 21))
res = list(filter((lambda n: n%2==0),l))
print(res)
# 输出
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]