This article describes the Python3 higher-order functions map, reduce, filter the sample code in this article to tell you in great detail, has a certain value for references, a friend in need can refer to the
parameters of the function to receive variable, then a function can receive another function as a parameter, this function is called to higher order functions.
Note wherein: map and a return filter inert sequence, iterables, must be transformed to list
>>> a = 3.1415
>>> round(a,2)
3.14
>>> a_round = round
>>> a_round(a,2)
3.14
>>> def func_devide(x, y, f):
return f(x) - f(y)
#传递参数为函数
print(func_devide(9.3, 3.2, round))
- map function
map () function accepts two arguments, a function, a is Iterable, map the incoming function sequentially applied to each element of the sequence, and the result returned as the new Iterator.
>>> print(list(map(str, [1, 2, 3])))
['1', '2', '3']
>>> dt = map(str,[-1,2,3,4,5,-34,-45,-23.454])
>>> dt
<map object at 0x10f431dd8>
>>> list(dt)
['-1', '2', '3', '4', '5', '-34', '-45', '-23.454']
>>> dt = map(abs,[-1,2,3,4,5,-34,-45,-23.454])
>>> list(dt)
[1, 2, 3, 4, 5, 34, 45, 23.454]
Note error: TypeError: 'map' object is not callable
Reasons generally appear iterative objects (str, abs, etc.) or function (Map) is modified, the original function is no longer, resulting in non-iterative object appears
- reduce function
reduce to a function on a sequence [x1, x2, x3, ...], the function must receive two parameters, and continue to reduce the result of the next element in the sequence is calculated as the accumulator. It returns the final result of a calculation function takes two parameters:
def add(x,y):
... return x + y
...
>>> reduce(add,[1,2,3,4,5,6,7,8,9,10])
55
>>> def concate(x,y):
... return str(x)+str(y)
...
>>> reduce(concate,[1,2,3,4,5,6,7,8,9,0])
'1234567890'
map function and reduce binding strings do revolutions integer (integer or string rpm)
>>> str = '12121212132323'
>>> dic_str_int = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
>>> def str_arr(x):
... dic_str_int = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
... return dic_str_int[x]
...
>>> def int_dum(x,y):
... return 10*x + y
...
>>> reduce(int_dum,map(str_arr,str))
12121212132323
Example, converting data within the list to uppercase, initial caps
>>> names = ['jack','john','wilianmon','jobs','bill','gates']
>>> def str_upper(string):
... return string.upper()
...
>>> names = map(str_upper,names)
>>> list(names)
['JACK', 'JOHN', 'WILIANMON', 'JOBS', 'BILL', 'GATES']
>>> def str_capitialize(string):
... return string.capitalize()
...
>>> names = ['jack','john','wilianmon','jobs','bill','gates']
>>>
>>> names = map(str_capitialize,names)
>>> list(names)
['Jack', 'John', 'Wilianmon', 'Jobs', 'Bill', 'Gates']
List all of the elements within the parameters required product:
int_li = [2,3,5,10]
>>> reduce(lambda x, y: x*y,int_li)
300
>>> def func_mult(li=None):
... return reduce(lambda x, y: x*y,li)
...
>>> func_mult(int_li)
300
The above function may need to switch to a more convenient calling
'123.456' turned into an integer 123.456
Method one: cut off after stitching
def string_int(strs):
str_li = strs.split('.')
def str_int(str):
dic_str_int = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return dic_str_int[str]
int_1 = reduce(lambda x, y: x*10+y, list( map(str_int,str_li[0])))
int_2 = reduce(lambda x,y: x*10 + y,list(map(str_int,str_li[1])))
return int_1 + int_2/(10**(len(str_li)+1))
res = string_int('123.456')
print(res)
#结果:123.456
Method two: numerical string converted into pure
def string_int1(strs):
# 记住位置,替换
point_len = len(strs) - strs.find('.')-1
str_li = strs.replace('.', '')
def str_int(str):
dic_str_int = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return dic_str_int[str]
int_num = reduce(lambda x,y: x*10 + y,list(map(str_int,str_li)))
return int_num/(10**(point_len))
res = string_int1('123.456')
print(res)
#结果:123.456
- filter function
filter () also receives a function and a sequence. A sequence from the sieve elements qualified. And map () is different, filter () function is passed the sequentially applied to each element, and based on the return value is True or False decided to keep or discard the element.
Differences and map functions: Note
eg: Get all of the elements in the list integer types
def only_int(x):
try:
if isinstance(x, int):
return True
else:
return False
except ValueError as e:
return False
dt = filter(type_int,[1,2,3,3,'3232',-34.5,34.5])
>>> list(dt)
[1, 2, 3, 3]
We recommend the python learning sites to see how seniors are learning! From basic python script, reptiles, django, data mining, programming techniques, as well as to combat zero-based sorting data items, given to every love learning python small partner! Python veteran day have to explain the timing of technology, to share some of the ways to learn and need to pay attention to small details, click on Join us python learner gathering
summary
The above is a small series to introduce Python3 higher-order functions map, reduce, filter Detailed example, we want to help, if you have any questions please give me a message, Xiao Bian will promptly reply to your