python入门第十四天__内置函数 filter map reduce
Python filter() 函数
描述
filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
语法
以下是 filter() 方法的语法:
filter(function, iterable)
参数
- function -- 判断函数。
- iterable -- 可迭代对象。
返回值
返回列表。
例如,在一个list中,删掉偶数,只保留奇数,可以这么写:
def is_odd(n): return n % 2 == 1 list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])) # 结果: [1, 5, 9, 15]
把一个序列中的空字符串删掉,可以这么写:
def not_empty(s): return s and s.strip() list(filter(not_empty, ['A', '', 'B', None, 'C', ' '])) # 结果: ['A', 'B', 'C']
注意到filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list。
关于filter()方法, python3和python2有一点不同
python2中返回的是过滤后的列表, 而python3中返回到是一个filter类
filter类实现了__iter__和__next__方法, 可以看成是一个迭代器, 有惰性运算的特性, 相对python2提升了性能, 可以节约内存.
>>> def is_odd(n): return n%2==1 >>> filter(is_odd,[1,2,3,4,5,6,7,8,9,10,15]) <filter object at 0x0000000002F22E10>>>> a=filter(is_odd,[1,2,3,4,5,6,7,8,9,10,15]) >>> next(a) 1 >>> next(a) 3 >>> next(a) 5 >>> next(a) 7 >>> next(a) 9 >>> next(a) 15 >>> next(a) Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> next(a) StopIteration >>> next(a)
Python map() 函数
描述
map() 会根据提供的函数对指定序列做映射。
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
语法
map() 函数语法:
map(function, iterable, ...)
参数
- function -- 函数,有两个参数
- iterable -- 一个或多个序列
返回值
Python 2.x 返回列表。
Python 3.x 返回迭代器。
>>> list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])) [3, 7, 11, 15, 19] >>>
>>> def square(x): return x**2 >>> list(map(square,[1,2,3,4,5,6])) [1, 4,
Python reduce函数
from functools import reduce print(dir(reduce)) print(reduce.__doc__) -------------------------------------------------------------------------------- ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__'] reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. -------------------------------------------------------------------------------
reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
(lambda x, y: x+y, [1, 2, 3, 4, 5]) 相当于: ((((1+2)+3)+4)+5) reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
# from functools import reduce # def f(a,b): # return a*10+b # # def char2num(s): # digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} # return digits[s] # # print(reduce(f,map(char2num,'123456')))
整合一下 # from functools import reduce # digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} # def str2int(s): # def f(a,b): # return a*10+b # def char2num(s): # return digits[s] # return reduce(f,map(char2num,s)) # # print(str2int('123456')) # 简化一下 # from functools import reduce # # digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} # # def char2num(s): # return digits[s] # def str2int(str): # return reduce(lambda a,b:a*10+b, map(char2num,str)) # # print(str2int('123456'))
利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:
# def small_s(str): # return str[0].upper()+str[1:].lower() # # print(list(map(small_s,['adam', 'LISA', 'barT']))) def small_s(str): return str.title() print(list(map(small_s,['adam', 'LISA', 'barT'])))
利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
1 # -*- coding: utf-8 -*- 2 ''' 3 Created on 2018年6月26日 4 5 @author: Administrator 6 ''' 7 8 from functools import reduce 9 #把字符串'123.456'转换成浮点数123.456 10 digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} 11 def str2float(str_n): 12 13 def str2int(s): 14 def f(a,b): 15 return a*10+b 16 def char2num(s): 17 return digits[s] 18 return reduce(f,map(char2num,s)) 19 def str2xiaoshu(str): 20 def fn(x,y): 21 return x*10+y 22 def char2fnum(str): 23 return digits[str] 24 strnum=reduce(fn,map(char2fnum,str)) 25 26 # for i in range(len(str)): 27 # strnum/=10 28 strnum/=pow(10,len(str)) 29 return strnum 30 31 if '.' in str_n: 32 str_n=str_n.split('.') 33 return str2int(str_n[0])+str2xiaoshu(str_n[1]) 34 else: 35 return str2int(str_n) 36 # return str2int(get_point_place(str_n)[0]) 37 38 39 print(str2float('9654.35'))
40 print(str2float('9654'))
结果:
9654.35 9654
1 # -*- coding: utf-8 -*- 2 ''' 3 Created on 2018年6月26日 4 5 @author: Administrator 6 ''' 7 #回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数: 8 from functools import reduce 9 def same_cb(number_int): 10 11 number_str=str(number_int) 12 number_str_new=[] 13 for i in number_str: 14 number_str_new.append(int(i)) 15 number_str_new.reverse() 16 def fn(x,y): 17 return 10*x+y 18 number_new=reduce(fn, number_str_new) 19 if number_new==number_int: 20 return number_int 21 22 # for i in range(1,20): 23 # print(same_cb(i)) 24 25 26 if list(filter(same_cb, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]: 27 print('测试成功!') 28 else: 29 print('测试失败!')
结果:
测试成功!
直接用字符比较:
from functools import reduce import copy def same_cb(number_int): number_str=str(number_int) number_str_new=[] for i in number_str: number_str_new.append(int(i)) number_str_list=copy.deepcopy(number_str_new) number_str_new.reverse() if number_str_new==number_str_list: return number_int if list(filter(same_cb, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]: print('测试成功!') else: print('测试失败!')
结果:
测试成功!
示例:
1 # -*- coding: utf-8 -*- 2 ''' 3 Created on 2018年6月26日 4 5 @author: Administrator 6 ''' 7 # #回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数: 8 from functools import reduce 9 def same_cb(num): 10 number=num 11 list_new=[] 12 while True: 13 if number>0: 14 num_new=divmod(number, 10) 15 list_new.append(num_new[1]) #yushu 16 number=num_new[0] #shang 17 else: 18 break 19 def sum2ji(x,y): 20 return 10*x+y 21 if num==reduce(sum2ji, list_new): 22 return num 23 #return list_new 24 #return reduce(sum2ji, list_new) 25 26 27 print(same_cb(454)) 28 if list(filter(same_cb, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]: 29 print('测试成功!') 30 else: 31 print('测试失败!')
结果:
454
测试成功!

浙公网安备 33010602011771号