Home  >  Article  >  Backend Development  >  Python basic tutorial: How to use Map

Python basic tutorial: How to use Map

高洛峰
高洛峰Original
2017-02-21 10:31:351661browse

Python Map

Map maps a function to all elements of an input list. The specification of Map is: map(function_to_apply, list_of_inputs)
Most of the time, we need to pass all the elements in the list to a function one by one and collect the output. For example:

items = [1, 2, 3, 4, 5] 
squared = [] 
for i in items: 
  squared.append(i**2)

Using Map allows us to solve this problem in a simpler way.

items = [1, 2, 3, 4, 5] 
squared = list(map(lambda x: x**2, items))

Most of the time, we will use the anonymous function lambda in python to cooperate with map. Not only for a list of inputs, but we can also use it for a list of functions.

def multiply(x): 
  return (x*x) 
def add(x): 
  return (x+x) 
funcs = [multiply, add] 
for i in range(5): 
  value = list(map(lambda x: x(i), funcs)) 
  print(value)

The output of the above program is:

# Output: 
# [0, 0] 
# [1, 2] 
# [4, 4] 
# [9, 6] 
# [16, 8]

Thanks Reading, I hope it can help everyone, thank you for your support of this site!

For more articles related to python basic tutorial on how to use Map, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn