Many languages provide processing mechanisms for parameters or variables. As a flexible Python, it provides some special methods for function processing.
Filter (function, sequence ):Execute function (item) in sequence for items in sequence, and combine items with the execution result of True into a List/String/Tuple.
Map (function, sequence ):Execute function (item) in sequence for items in sequence. See the execution result to form a List.
Reduce (function, sequence, starting_value ):Call the function for sequential iteration of items in sequence
Sum (sequence ):Accumulate elements in the Set
The following is a simple example of the above description:
Copy codeThe Code is as follows:
_ Author _ = 'admin'
From functools import reduce
# It is mainly used to conceal that map can pass elements in a sequence to a special function for processing.
Def map_demo ():
# Define a function for converting letters into uppercase letters
Def to_upper (ch ):
Return str (ch). upper ()
# Apply the to_upper function to each letter in the given string
Print (list (map (to_upper, "asdfasdfuasdlaksdjf". split ())))
# Mainly uses a Boolean-worthy function to filter elements
Def filter_demo ():
Def is_alnum (ch ):
Return ch. isalnum ()
#! Se will be filtered out
Test_list = ['sdas', '123d ','! Se ', 'Sun asstephen']
# Based on specific functions
Print (list (filter (is_alnum, test_list )))
# List-based Derivation
Print (list (x for x in test_list if x. isalnum ()))
# Anonymous Functions
Print (list (filter (lambda x: x. isalnum (), test_list )))
# The main function of reduce is to use two elements in the list to call a function iteratively and finally get a result.
# Add from functools import reduce to be displayed in python3
# In this example, the running process is roughly 1 + 2 = 3, and 3 + 4 = 7 + 4 .......
Def performance_demo ():
Print (reduce (lambda x, y: x + y, range (1, 10 )))
# Use the sum function to accumulate values in the list
Def sum_demo ():
Print (sum (range (10 )))
If _ name _ = "_ main __":
# Map_demo ()
# Filter_demo ()
# Performance_demo ()
Sum_demo ()