Python基础学习（六）—–函数应用

756-周同学

,

一. 参数

1. 匹配

1. 位置匹配
2. 关键字匹配
def func(a,b,c):
print(a,b,c)

func(c=1,a=2,b=3)

1. 默认值（调用时省略传值）
def func(a,b=2,c=3):
print(a,b,c)

func(1)

1. *args 任意数量参数
def avg(*scores):
return sum(scores)/len(scores)

scores=(98.2,88.4,70,65)
result=avg(*scores)
print(result)

1. **kwargs 字典
def display_employee(**employee):
print(employee)

display_employee(name='tom',age=22,job='dev')


二. Lambda表达式

2. 基本表达式

f= lambda name: print(name)
f2 = lambda x,y: x+y

f('tom')
print(f2(5,3))

def hello_chinese(name):
print("你好:",name)

def hello_english(name):
print('hello:',name)

hello = hello_chinese
hello = lambda name: print('hello:',name)

hello('tom')

def hello_chinese(name):
print('hello:',name)

def hello_english(name):
print('hello:',name)

def hello_japanese(name):
print('hello:',name)

def hello(action,name): #action是一个函数
action(name)

hello(hello_chinese,'Tom')
hello(lambda name: print('hhh',name),'Tom')


三. 高级工具

1. map函数，可迭代对象

l = list(range(1,21))

res=[]

return x+5

#1. 使用循环
for x in l:
res.append(x+5)

#2. 使用推导
res=[x+5 for x in l]

#3.map()
res = list(map(lambda n: n**2,l))

print(res)


2. filter函数，可迭代对象(不是list）

l = list(range(1,11))

def even_number(x):
return x%2 == 0

res = filter(even_number,l)
res = filter(lambda n : n%2 ==0,l)
res = [x for x in l if x%2 == 0]

for n in res:
print(n,end=' ')


Vieu3.3主题

Q Q 登 录