Python函数进阶

包含以下几部分内容:函数的参数传递、函数文档、lambda匿名函数、map/filter/zip/reduce/enumerate函数

一、函数的参数传递

1、参数定义与传递的基本顺序

位置参数——> 关键词参数——>可变数量参数(*args,**args)

def test_fun(a,b=6,*c,**d):
  print("a = ",a,",b = ",b,",c = ",c,",d = ",d)

>>>test_fun(1)
a = 1

>>>test_fun(1,2)
a =  1 ,b =  2 ,c =  () ,d =  {}
    
>>>test_fun(1,2,3)
a =  1 ,b =  2 ,c =  (3,) ,d =  {}
    
>>>test_fun(1,2,3,4)
a =  1 ,b =  2 ,c =  (3, 4) ,d =  {}

test_fun(1,2,3,x = 4)
a =  1 ,b =  2 ,c =  (3,) ,d =  {'x': 4}
    
>>>test_fun(a=1)
a =  1 ,b =  6 ,c =  () ,d =  {}
    
>>>test_fun(a=1,b=2)
a =  1 ,b =  2 ,c =  () ,d =  {}
    
>>>test_fun(a=1,b=2,c=3)
a =  1 ,b =  2 ,c =  () ,d =  {'c': 3}
    
>>>test_fun(1,b=2)
a =  1 ,b =  2 ,c =  () ,d =  {}
   
>>>test_fun(1,2,3,4,x=1)
a =  1 ,b =  2 ,c =  (3, 4) ,d =  {'x': 1}
    
>>>test_fun(1,2,3,4,5,6,x=1,y=2,z=3)
a =  1 ,b =  2 ,c =  (3, 4, 5, 6) ,d =  {'x': 1, 'y': 2, 'z': 3}
    
>>>test_fun(1,2,3,4,b=3)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-14-9dd806cee30e> in <module>()
----> 1 test_fun(1,2,3,4,b=3)
    

TypeError: test_fun() got multiple values for argument 'b'

二、函数文档

  • 函数定义语法:
    def 函数名([参数列表]):
      ‘’‘注释’’’
      函数体

例:

def fun():
    '''This is a function
    it will realize some function'''
    print('Hi,welcome to my function!')

>>>print(fun.__doc__)
This is a function
    it will realize some function
    
>>>help(fun)
Help on function fun in module __main__:

fun()
    This is a function
    it will realize some function

三、lambda匿名函数

lambda表达式可以用来声明匿名函数,也就是没有函数名 字的临时使用的小函数,尤其适合需要一个函数作为另一个函数参数的场合。也可以定义具名函数。

lambda表达式只可以包含一个表达式,该表达式的计算结 果可以看作是函数的返回值,不允许包含复合语句,但在表达式中可以调用其他函数。

<函数名> = lambda <参数> : <表达式>

      等价于

def  <函数名>(<参数>):
    函数体
    return <返回值>

>>>f = lambda x,y,z: x+y+z      #可以给lambda表达式起名字
>>>f(1,2,3)                     #像函数一样调用
6

>>>g = lambda x,y=2,z=3: x+y+z  #参数默认值
>>>g(1)
6
>>>g(2,z=4,y=5)                 #关键参数
11

>>>f = lambda x:x+5
>>>f(3)
8

>>>sorted(['abc','afe','acb'],key=lambda x:(x[0],x[2]))
['acb', 'abc', 'afe']


lambda表达式中可以使用任意复杂的表达式,但必须只编写一个表达式
可以使用lambda表达式定义有名字的函数
一般情况下,建议使用def定义的普通函数

四、map/filter/zip/reduce/enumerate

0、range函数

语法:range(stop)
   range(start, stop[, step])

1、map函数
map() 会根据提供的函数对指定序列做映射
第一个参数function以参数序列中的每一个元素调用function函数,返回包含每次function函数返回值的新列表

语法:
map(function,iterable,…)     function —— 函数
                iterable —— 一个或多个序列

>>>def square(x):
    return x ** 2
>>>map(square, [1,2,3,4,5])
<map at 0x1529453c198>


>>>def square(x):
    return x ** 2
>>>list(map(square, [1,2,3,4,5]))
[1, 4, 9, 16, 25]



>>>map(lambda x: x ** 2, [1,2,3,4,5])
<map at 0x1529453c240>

>>>list(map(lambda x: x ** 2, [1,2,3,4,5]))
[1, 4, 9, 16, 25]

>>>for i in map(lambda x,y : x*y, [1,3,5,7,9],[2,4,6,8,10]):
    print(i,end = '\t')
2	12	30	56	90	



>>>def add(x,y,z):
    return x+y+z
list1 = [1,2,3]
list2 = [1,2,3,4]
list3 = [1,2,3,4,5]
res = map(add,list1,list2,list3)
>>>print(list(res))
[3,6,9]
 
 
>>>x,y,z = map(str,range(3))
>>>print(y)
1
 
    
>>>x,y = map(int,['1','2'])
>>>x+y
3

2、filter函数

  • filter函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表,如果指定函数为None,则返回序列中等价于True 的元素
  • 接受两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回Ture或False,最后将返回True的元素放到新列表中

注意function函数只能接受一个参数,且返回值是True或False

>>> seq = ['foo', 'x41', '?!', '***'] 
>>>> def func(x): 
         return x.isalnum()         #测试是否为字母或数字

>>> filter(func, seq)                   #返回filter对象 
<filter object at 0x000000000305D898> 
>>> list(filter(func, seq))             #把filter对象转换为列表 
['foo','x41']

def is_odd(n):
    return n % 2 == 1
newlist = filter(is_odd, [1,2,3,4,5,6,7,8,9,10])

>>>print(newlist)
<filter object at 0x0000000005815CC0>

def is_odd(n):
    return n % 2 == 1
newlist = filter(is_odd, [1,2,3,4,5,6,7,8,9,10])

>>>print(newlist)
[1,3,5,7,9]

>>>list(filter(None,[0,1,2,3,0,0]))
[1,2,3]


>>>list(filter(lambda x:x>2,[0,1,2,3,0,0]))
[3]

3、zip函数

  • zip函数用于将可迭代对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表
  • 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用*号操作符,可以将元组解压为列表

语法:
zip([iterable,…])    (iterable —— 一个或多个迭代器)

a = [1,2,3]
b = [4,5,6]
>>>zip(a,b)
<zip at 0x5a1fa08>


a = [1,2,3]
b = [4,5,6]
>>>list(zip(a,b))
[(1,4),(2,5),(3,6)]


a = [1,2,3]
b = [4,5,6]
zipped = zip(a,b)
>>>list(zip(*zipped))
[(1.2.3),(4,5,6)]       #与zip相反,*zipped可以理解为解压,返回二维矩阵式


a = [1,2,3,8]
b = [4,5,6,7]
c= [3,4,7,7]
>>>list(zip(a,b,c))
[(1, 4, 3), (2, 5, 4), (3, 6, 7), (8, 7, 7)]



a = [1,2,3]
b = [3,4,5]
zipped = zip(a,b)
>>>list(zip(*zipped))
[(1, 2, 3), (3, 4, 5)]



a = ['name','age','sex']
b = ['Dong','38','Male']
c = dict(zip(a,b))
>>>c
{'name': 'Dong', 'age': '38', 'sex': 'Male'}



>>>dict(zip([1,2],[3,4]))
{1: 3, 2: 4}


4、enumerate函数

enumerate()函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用于for循环当中

语法:
enumerate(seq,[start = 0])    (seq:一个支持迭代对象,start:下标起始位置)

seasons = ['spring','summer','fall','winter']
>>>list(enumerate(seasons))
[(0,'spring'),(1,'summer'),(2,'fall'),(3,'winter')]

>>>list(enumerate(seasons,start = 1))
[(1,'spring'),(2,'summer'),(3,'fall'),(4,'winter')]



i = 0                                                seq = ['tom','jerry','bob'] 
seq = ['tom','jerry','bob']                          for i,element in enumerate(seq):
for element in seq:                                      print(i,element)
    print(i,seq[i])                                  
    i += 1                      等价于
 
 0 tom                                               0 tom
 1 jerry                                             1 jerry
 2 bob                                               2 bob



x = [3, 2, 3, 3, 4]
>>>[index for index, value in enumerate(x) if value==3] 
[0,2,3]


>>>[index for index, value in enumerate([3,5,7,3,7]) if value == max([3,5,7,3,7])] 
[2,4]


x = [1,2]
>>>list(enumerate(x)) 
[(0,1),(1,2)]


5、reduce函数

reduce()函数会对参数序列中元素进行累积
函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给reduce中的函数function(有两个参数)先对集合中的1、2个元素进行操作,得到的结果再与第三个数据用function函数运算,最后得到一个结果

语法:
reduce(function,iterable[,initializer])

  • function :函数,有两个参数
  • iterable :可迭代对象
  • initializer:可选,初始参数

在Python3中,需要通过引用functools模块来调用reduce()函数
from functools import reduce

from functools import reduce
def add(x,y):
    return x+y
reduce(add, [1,2,3,4,5])
15


from functools import reduce
reduce(lambda x, y: x+y, [1,2,3,4,5])
15


from functools import reduce
def add(x,y):
    return x+y
print(reduce(add,range(1,101)))
5050

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值