Python basic tutorial: How to use Map

高洛峰
Release: 2017-02-21 10:31:35
Original
1707 people have browsed it

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)
Copy after login

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))
Copy after login

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)
Copy after login

The output of the above program is:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template