Basic python tutorial-how to use Map, basic python tutorial map

Source: Internet
Author: User

Basic python tutorial-how to use Map, basic python tutorial map

Python Map

Map maps a function to all elements in an input list. Map specifications: map (function_to_apply, list_of_inputs)
Most of the time, we need to pass all the elements in the list one by one to a function 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 use the anonymous function lambda in python to work with map. We can use a list function as well as a list input.

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 above program output is:

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

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.