(1)trim()函数的实现(利用切片操作实现trim函数,去除字符串首尾的空格):
def trim(s):
if len(s)==0:
return s
while s[0]==' ':
s=s[1:]
while s[-1]==' ':
s=s[:-1]
return s
(2)在list列表中寻找最大值和最小值:
def find(L):
(min,max)=(L[0],L[0])
for x in list(L):
if min>x:
min=x
if max<x:
max=x
return min,max
L=[2,3,4,1,5,6]
x,y=find(L)
print(x,y)
3、可迭代对象,生成器与迭代器的区别
定义可迭代对象,必须实现_iter_方法;定义迭代器,必须同时实现_iter_方法和next方法
- 可迭代对象:可以直接作用于for循环的对象统称为可迭代对Iterablde,也可以使用isinstance()判断一个对象是否为Iterable对象
from collections import Iterable
isinstance([],Iterable)
得到的结果为True
2. 可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator
from collections import Iterator
isinstance(x for x in range(10),Iterator)
(1)_iter_方法
该方法返回的是当前对象迭代器类的实例;可迭代对象和迭代器都要实现这个方法,因此该方法有两种写法:
- 用于可迭代对象类的写法,返回该可迭代对象迭代器类的实例
- 用于迭代器类的写法,直接返回self(即自己本身),表示自身既是自己的迭代器
(2)next方法
返回迭代过程中的每一步,最后超出边界时抛出StopIteration异常
4、高阶函数:变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数叫做高阶函数。如下例:
def add(x,y,f):
return f(x)+f(y)
print(add(-5,6,abs))
(1)map函数:map函数接收两个参数,第一个是函数,第二个是Iterable,将传入的参数依次作用到序列的每个元素上,把结果作为新的Iterator返回
def f(x):
return x*x
r=map(f,[1,2,3,4,5])
print(list(r))
例:使用map函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字
def normalize(name):
return name.capitalize()//将首字母转化为大写
L1=['Army','boy','girl']
L2=list(map(normalize,L1))
print(L2)
(2)reduce函数:接收两个参数,第一个为函数,第二个为Iterable,对序列的第一个元素应用完函数后,把结果继续和序列的下一个元素做累积运算
reduce(f,[x1,x2,x3])=f(f(f(x1,x2),x3),x4)
(3)filter函数:用于过滤序列,将函数作用在序列中的每个元素上,与map函数不同的是,filter函数会根据返回值是True还是False进行过滤,留下返回值为True的元素
#把序列中的空字符串删掉
def not_empty (s):
return s and s.strip()
print(list(filter(not_empty),['A','','B',' ']))
#['A','B']
(4)匿名函数:lambda(冒号前的x,代表函数的参数,冒号后为函数的表达式)
f=lambda a,b,c:a+b+c
print(f)
print(f(2+3+4))
g=[lambda a:a*2,lambda b:b*3,lambda c:c*4]
print(g[0](6),g[1](7),g[2](8))
#9
#12 21 32
(5)eval()函数
eval(source,globals,locals[])->value
source:一个python表达式或函数compile()返回的代码对象
globals:可选,必须是dictionary
locals:可选,任意映射函数
(6)递归函数:
def test01(n):
print("test01",n)
if n==0:
print("over")
else:
test01(n-1)
print("test01***",n)
test01(4)
#test01 4
#test01 3
#test01 2
#test01 1
#test01 0
#over
#test01*** 0
#test01*** 1
#test01*** 2
#test01*** 3
#test01*** 4
例:使用递归函数计算阶乘
def fact(n):
if n==1:
return 1
return n*fact(n-1)
for i in range(1,6):
print(i,'!=',fact(i))
#1 != 1
#2 != 2
#3 != 6
#4 != 24
#5 != 120
(6)装饰器:在代码运行期间动态增加功能的方式,称之为装饰器