Python基础14(内置函数总二及匿名函数)
内置函数-----filter和map
filter
filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。
例如,要从一个list [1, 4, 6, 7, 9, 12, 17]中删除奇数,保留奇数,首先,要编写一个判断奇数的函数:
1 def add(x): 2 return x % 2 == 1
然后,利用filter()过滤掉偶数:
a = filter(add, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
结果:
print(list(a)) #[1, 3, 5, 7, 9]
利用filter(),可以完成很多有用的功能,例如,删除 None 或者空字符串:
1 def is_not_empty(s): 2 return s and len(s.strip()) > 0 3 r = filter(is_not_empty,['sts', None, ' ']) 4 print(list(r))
注意: s.strip(rm) 删除 s 字符串中开头、结尾处的 rm 序列的字符。
当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' '),如下:
a = '123 ' print(a.strip())
1 a = '\t\t\n123\t\t\n\n' 2 print(a.strip())
请利用filter()过滤出1~100中平方根是整数的数,即结果应该是:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
1 import math # 导入数学常量 2 def is_sqr(x): 3 return math.sqrt(x) % 1 == 0 # .sqrt为开根号 4 s = filter(is_sqr, range(1, 101)) 5 print(list(s))
map
Python中的map函数应用于每一个可迭代的项,返回的是一个结果list。如果有其他的可迭代参数传进来,map函数则会把每一个参数都以相应的处理函数进行迭代处理。map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。
有一个list, L = [1,2,3,4,5,6,7,8],我们要将f(x)=x^2作用于这个list上,那么我们可以使用map函数处理。
1 L = [1,2,3,4,5] 2 def is_square(x): 3 return x * x 4 s = map(is_square,L) 5 print(list(s))
sorted
对List、Dict进行排序,Python提供了两个方法
对给定的List L进行排序,
方法1.用List的成员函数sort进行排序,在本地进行排序,不返回副本
方法2.用built-in函数sorted进行排序(从2.4开始),返回副本,原始输入不变
sorted(iterable, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customise the sort order, and the
reverse flag can be set to request the result in descending order.
-----------------------------------------------------------------------------
参数说明:
iterable:是可迭代类型;
key:传入一个函数名,函数的参数是可迭代类型中的每一项,根据函数的返回值大小排序;
reverse:排序规则. reverse = True 降序 或者 reverse = False 升序,有默认值。
返回值:有序列表
1 l1 = [-1,2,-2,-4,0,1,3,5,7] 2 l2 = sorted(l1,key=abs) 3 print(l1) 4 print(l2)
列表按照每一个元素的len排序
1 l = ['1','2',[1,2,3],'sssssss'] 2 l2 = sorted(l,key=len) 3 print(l2)
匿名函数
匿名函数:为了解决那些功能很简单的需求而设计的一句话函数
#这段代码 def calc(n): return n**n print(calc(10)) #换成匿名函数 calc = lambda n:n**n print(calc(10))

匿名函数格式
1 函数名 = lambda 参数 :返回值 2 3 #参数可以有多个,用逗号隔开 4 #匿名函数不管逻辑多复杂,只能写一行,且逻辑执行结束后的内容就是返回值 5 #返回值和正常的函数一样可以是任意数据类型
请把以下函数变成匿名函数 def add(x,y): return x+y 结果 kkk = lambda x, y: x+y
上面是匿名函数的函数用法。除此之外,匿名函数也不是浪得虚名,它真的可以匿名。在和其他功能函数合作的时候
1 l=[3,2,100,999,213,1111,31121,333] 2 print(max(l)) 3 4 dic={'k1':10,'k2':100,'k3':30} 5 6 7 print(max(dic)) 8 print(dic[max(dic,key=lambda k:dic[k])])
1 res = map(lambda x:x**2,[1,5,7,4,8]) 2 for i in res: 3 print(i) 4 5 输出 6 1 7 25 8 49 9 16 10 64
1 res = filter(lambda x:x>10,[5,8,11,9,15]) 2 for i in res: 3 print(i) 4 5 输出 6 11 7 15
面试题
现有两个元组(('a'),('b')),(('c'),('d')),请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]
1 #答案一 2 test = lambda t1,t2 :[{i:j} for i,j in zip(t1,t2)] 3 print(test(t1,t2)) 4 #答案二 5 print(list(map(lambda t:{t[0]:t[1]},zip(t1,t2)))) 6 #还可以这样写 7 print([{i:j} for i,j in zip(t1,t2)])
1 1.下面程序的输出结果是: 2 d = lambda p:p*2 3 t = lambda p:p*3 4 x = 2 5 x = d(x) 6 x = t(x) 7 x = d(x) 8 print x 9 10 2.现有两元组(('a'),('b')),(('c'),('d')),请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}] 11 12 3.以下代码的输出是什么?请给出答案并解释。 13 def multipliers(): 14 return [lambda x:i*x for i in range(4)] 15 print([m(2) for m in multipliers()]) 16 请修改multipliers的定义来产生期望的结果。

浙公网安备 33010602011771号