Map
Map will be a function mapped to input all the elements of a list. This is its specification:
specification
map(function_to_apply, list_of_inputs)
Most of the time, we want to list all the elements one by one passed to a function, and collect output. for example:
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
Map allows us to use a simple and beautiful way to achieve much more. That's it:
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
Most of the time, we use anonymous functions (lambdas) to match the map, so I did the same thing at the top. Not only to enter a list, we can even function for a list!
def multiply(x):
return (x*x)
def add(x):
return (x+x)
funcs = [multiply, add]
for i in range(5):
value = map(lambda x: x(i), funcs)
print(list(value))
# 译者注:上面print时,加了list转换,是为了python2/3的兼容性
# 在python2中map直接返回列表,但在python3中返回迭代器
# 因此为了兼容python3, 需要list转换一下
Filter
Filtration filter elements in the list, and returns a list of all of the elements to meet the requirements posed, in line with requirements i.e., when the return value is True function maps the element to a brief example of this is:
number_list = range(-5, 5)
less_than_zero = filter(lambda x: x < 0, number_list)
print(list(less_than_zero))
# 译者注:上面print时,加了list转换,是为了python2/3的兼容性
# 在python2中filter直接返回列表,但在python3中返回迭代器
# 因此为了兼容python3, 需要list转换一下
This filter is similar to a for loop, but it is a built-in function, and faster.
Reduce
When you need to do some calculations on a list and returns the result, Reduce it is a very useful function. For example, when you need to calculate the product of a list of integers.
Usually in python you can use basic for loop to accomplish this task.
Now let's try to reduce:
from functools import reduce
product = reduce( (lambda x, y: x * y), [1, 2, 3, 4] )
lambda expressions
lambda expression is a function of his party.
They are also known as anonymous functions in other languages. If you do not want to use twice a function in your program, you might want to use lambda expressions, and they are exactly the same as an ordinary function.
prototype
lambda 参数:操作(参数)
example
add = lambda x, y: x + y
print(add(3, 5))
# Output: 8
That there are some application examples of lambda expressions, can be used in some special cases:
List sorted
a = [(1, 2), (4, 1), (9, 10), (13, -3)]
a.sort(key=lambda x: x[1])
print(a)
# Output: [(13, -3), (4, 1), (1, 2), (9, 10)]
Parallel sorting list
data = zip(list1, list2)
data.sort()
list1, list2 = map(lambda t: list(t), zip(*data))