美文网首页
Python学习笔记-函数

Python学习笔记-函数

作者: 在Azkaban写代码 | 来源:发表于2018-09-27 17:29 被阅读8次

1、 收集参数(可变参数)

  • 将不确定的参数个数,打包成元组,调用的时候需要关键字指定
def test1(* p1, extra = "8"):
    print(len(p1))
    print(extra)

def test2 (* p2):
    print(len(p2))
    print(p2[1]) #解包后才能获取

a = [1,2,3,4,5,6]
test1(a)
test2(*a) #解包

>>>
1
8
6
2

2、所有函数都有返回值

  • 不写return语句, 默认return None
def hello():
    print("hello! ")
print(hello())

>>>
hello! 
None

3、 不能在函数中修改全局变量,函数会在函数内部新建一个名字一样的局部变量替换掉,如果需要修改,需要在加上关键字global

global count

  • nonlocal关键字,可以修改外部函数里的局部变量
def hello():
    x = 5
    def fun():
        nonlocal x
        x *= 5
        return x
    return fun #返回函数无()
print(hello()())

>>>
25

4、lambda表达式,不用考虑命名,

g = lambda x, y = x+y

5、filter() 和 map()

  • filter(),第一个参数可以是函数,也可以是None就会将第二个可迭代的数据里为Ture的筛选出来
    list(filter(None,[1,0,False,Ture])) #结果为[1,Ture]
    list(filter(lambda x: x%2 , range(10))) # 获取到奇数

  • map() ,第一个函数,第二为可迭代序列,返回所有加工后的元素构成的新序列
    list(map(lambda x: x*2 , range(10))) #结果为 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

相关文章

网友评论

      本文标题:Python学习笔记-函数

      本文链接:https://www.haomeiwen.com/subject/lyudoftx.html