Python-function programming, python-Function
Map () function:
Two parameters are received: one is a function and the other is a sequence. The map function applies the input function to each element of the sequence at a time, if any input function is returned, the result is returned as a new sequence. returns an empty sequence (a string is also a sequence)
Filter () function:
Reduce () function:
Two parameters are accepted: one is a function, and the other is a sequence. The reduce function applies the input function (which must have two parameters) to the sequence. The output result is further computed with the next element of the sequence, the final result returned by the reduce () function is determined by the result returned by the input function.
Lambda expressions, anonymous Functions
Let's take an example: Call the map () function and reduce () function to calculate the sum of the numbers and numbers composed of an integer.
# _ * _ Coding: UTF-8 _*_
"""
2016-06-05
The program calls the map () function and reduce () function,
Returns the number that is composed of an integer and its sum.
"""
Num = input ('enter an integer :')
# Converting integers into strings
S = str (num)
# Define map parameter functions
Def f (s ):
# Character and number dictionary
Dic = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, "6": 6, '7': 7, '8': 8, '9': 9, '0': 0}
Return dic [s]
# Define reduce parameter functions
Def add (x, y ):
Return x + y
# Call the map () function to convert the string to the corresponding numeric sequence and print
S = map (f, s)
Print "the constituent Number of the input integer % d is % s" % (num, s ),
# Call the reduce function, sum the number sequence, and print
Sum = reduce (add, s)
Print "and Sum: % d" % Sum
Program Execution result:
The following is an example of Word Frequency Statistics:
Str = "an apple a banana three apple a desk"
List = str. split ('')
Def fun (x, y ):
If y in x:
X [y] = x [y] + 1
Else:
X [y] = 1
Return x
Result = reduce (fun, list ,{})
# The output result is
>>>{ 'A': 2, 'apple': 2, 'three ': 1, 'any': 1, 'desk': 1, 'Banana ': 1}