Python学习07_函数类型

本文深入探讨了Python中的各种函数类型,包括递归函数、匿名函数(lambda)、高阶函数,并详细介绍了filter、map、reduce等高级函数的使用方法及应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数类型

递归函数

在一个函数体内部,调用函数本身,被称为递归函数。

def f(n):
    if n == 1:
        return 1
    if n == 2:
        return 1
    else:
        return f(n-1) + f(n-2)
print(f(10))

55
def func(n):
    print(n)
    if int(n/2) == 0:
        return n
    return func(int(n/2))
print(func(10))

10
5
2
1
1

匿名函数(lambda)

格式:
lambda para1,para2, ....,paraN : expression using paras
f = lambda x,y,z: x+y+z
print(type(f))
print(f(1,2,3))

6

高阶函数

高阶函数:把一个函数名,以实参的形式,传递给这个函数的形参,这个函数就是高阶函数。

def add(a,b,c):
    return c(a) + c(b)
a_value = add(-9, 1,abs)
print(a_value)

10
def pow(x):
    return x**2
def add(a,b,c):
    return c(a) + c(b)
a_value = add(1, 2,pow)
print(a_value)

5
li = ['zhejiang','un','city','college']
def s(sr):
    return sr.startswith('c')
def e(sr):
    return sr.endswith('ty')
def f(func,para):
    ret = []
    for i in para:
        if not func(i):
            ret.append(i)
    return ret
print(f(s,li))
print(f(e,li))

['zhejiang', 'un']
['zhejiang', 'un', 'college']

filter 函数

li = ['zhejiang','un','city','college']
def f(para):
    ret = []
    for i in para:
        if not i.startswith('c'):
            ret.append(i)
    return ret
print(f(li))
li = ['zhejiang','un','city','college']
def f(func,para):
    ret = []
    for i in para:
        if not func(i):
            ret.append(i)
    return ret
fl = filter(lambda sr:not sr.endswith('ty'),li)
print(list(fl))
f2 = filter(lambda sr:not sr.startswith('c'),li)
print(list(f2))

功能:

  • 过滤掉序列中不符合函数条件的元素。当序列中要需要保留的元素可以用来某些函数描述时,就应该想到filter函数。
  • 调用格式:
    • filter(function, sequence)
    • function—>可以是自定义的函数,也可以是匿名函数
    • sequence—>列表,元组,字符串

map函数(映射)

功能

  • 求一个序列或者多个序列进行函数映射后的值。(用list()强转)

格式

  • map(function,iterable1,iterable2)
    
    • function 的参数可以不止一个
    • iterable1, iterable2就是传入function的参数
li = [1,2,3,4,5]
res = map(lambda x:x+1,li)
print(list(res))
x = [1,2,3,4,5]
y = [2,3,4,5,6]
res = map(lambda x,y:x*y+2,x,y)
print(list(res))

[4, 8, 14, 22, 32]

reduce函数

  • 功能
    • 对一个序列进行压缩运算,得到一个value,
    • Python2中,reduce()是内置函数,python3中,它被移植到functools模块中。
    • 使用from functools import reduce
  • 格式
    • reduce(function,iterable,[initiall])
      • function必须要传入两个参数
      • iterable 列表、元组
from functools import reduce
y = [2, 3, 4, 5, 6]
z = reduce(lambda x,y: x + y,y)
print(z)

20
from functools import reduce
y = [2, 3, 4, 5, 6]
z = reduce(lambda x,y: x + y,y,100)
print(z)

120
from functools import reduce
y = [2, 3, 4, 5, 6]
z = reduce(lambda x,y: x*10 + y,y)
print(z)

23456
from functools import reduce
y = [2, 3, 4, 5, 6]
z = reduce(lambda x,y: x*10 + y,y,10)
print(z)

1023456

apply函数

功能

  • pandas中,应用对象是pandas中的DataFrame或者Series

  • 直接对DataFrame或者Series应用函数

  • 对pandas中groupdy之后的聚合对象应用apply

    import numpy as np
    import pandas as pd
    a = np.random.randint(low=0,high=4,size=(2,4))
    print(a)
    data = pd.DataFrame(a)
    print(data)
    
    data.apply(lambda x: x*10)
    print(data.apply(lambda x: x*10))
    
    [[3 1 0 0]
     [2 0 3 2]]
       0  1  2  3
    0  3  1  0  0
    1  2  0  3  2
        0   1   2   3
    0  30  10   0   0
    1  20   0  30  20
    

zip函数

功能

  • 将可迭代对象作为参数,将对象中对应的元素打包成一个个元组,返回有这些元组构成的对象
  • 长度不一样的时候,以长度短的为准

注:

利用 * 号操作符,与zip相反,进行解压

格式:
zip(iterable1, iterable2, …)

  • iterable --> 两个或者多个可迭代序列(字符串,列表,元组,字典)
    • py2,由元组组成的列表
    • py3,返回的是一个对象,如果要得到一个列表
a = [1,2,3]
b = [4,5,6]
c = [4,5,6,7,8]
ziptest1 = zip(a, b)
print(list(ziptest1))

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

for i in ziptest1:
    print(i,end=" ")
    
(1, 4) (2, 5) (3, 6) 
a = [1,2,3]
b = [4,5,6]
c = [4,5,6,7,8]
ziptest1 = zip(b,c)

for i in ziptest1:
    print(i,end=" ")

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

Star_zip = zip(*ziptest1)
print(list(Star_zip))

[(4, 5, 6), (4, 5, 6)]

回文数练习

def num(x):
    if str(x) == str(x)[::-1]:
        return x
print(list(filter(num, range(1,1000))))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值