How to use map in python (detailed explanation of method)

藏色散人
Release: 2019-07-04 11:01:05
Original
42898 people have browsed it

How to use map in python (detailed explanation of method)

How to use map in python?

How to use map in python:

The prototype of the map function is map(function, iterable, ...), and its return result is a list.

The parameter function passes a function name, which can be built-in in python or customized. The parameter iterable passes an iterable object, such as a list, tuple, or string.

The meaning of this function is to apply the function to each element of iterable, and the result is returned in the form of a list. There is an ellipse after iterable, which means that multiple iterables can be passed. If there are additional iterable parameters, elements are taken from these parameters in parallel and the function is called.

Built-in function str():

str() is a built-in function of python. This example is to turn each element of the list/tuple/string into str type, and then return it in the form of a list

a=list(map(str,'python'))
print(a)
Copy after login

Output:

['p', 'y', 't', 'h', 'o', 'n']
Copy after login

Custom function:

def add(x,y):
    return x+y
list1=[1,2,3]
list2=[4,5,6]
a=list(map(add,list1,list2))
print(a)
Copy after login

Output:

[5, 7, 9]
Copy after login

Custom function ( If the lengths of the three lists are different):

def add(x,y):
    return x,y
list1 = [1,2,3]
list2 = [1,2,3,4]
a = list(map(add, list1, list2))
print(a)
Copy after login

Output:

[(1, 1), (2, 2), (3, 3)]
Copy after login

Related recommendations: "Python Tutorial"

The above is the detailed content of How to use map in python (detailed explanation of method). For more information, please follow other related articles on 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!