1:global将局部变量强制声明为全局变量:
def Fun():
count = 10
print(count)
Fun() #10
print(count) #NameError: name 'count' is not defined,
# count是局部变量,只能在定义的函数中查看
def Fun():
global count #将count声明为全局变量
count = 10
print(count)
Fun() #10
print(count) #10
2:nonlocal与global相似
def FunX():
x = 5
def FunY():
nonlocal x #在嵌套函数中将x强制声明为非局部变量
x *= x
return x
return FunY()
print(FunX())
3:闭包:如果在一个内部函数里,对未在外部作用域的变量进行引用,那么内部函数就叫闭包。(未尝试成功)
4:lambda:匿名表达式
#普通函数:
def add(x,y):
return x+y;
print(add(3,4))
#lambda表达式:
def add(x,y):
return x+y;
print(add(3,4))
5:filter(筛选标准(可None),筛选范围):把返回true的部分输出,返回False的舍弃
L = list(filter(None,[1,0,False,True])) #返回为真的内容
print(L) #输出[1, True]
def odd(x):
return x%2
tmp = range(10)
show = filter(odd,tmp)
print(list(show)) #输出:[1, 3, 5, 7, 9]
L = list(filter(lambda x:x%2,range(10)))
print(L) #同上结果
6:映射:map(函数,数值范围),返回的是新生成的值
L = list(map(lambda x : x*2,range(10)))
print(L) #输出:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]