Map in JS in map and python

Source: Internet
Author: User
Tags pow

The map in JS:

Because the map() method is defined in JavaScript Array , we call Array the map() method, passing in our own function, and get a new Array result:

  

function Pow (x) {    return x * x;} var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];arr.map (POW); [1, 4, 9, 16, 25, 36, 49, 64, 81]

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];arr.map(String); // [‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘]

Map in Python:

  

def f (x): ...      return x * x ... >>> r = Map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9])>>> list (R) [1, 4, 9, 16, 25, 36, 49, 64, 81 ]


map()The first parameter passed in is the f function object itself. Since the result r is one Iterator , it is an Iterator inert sequence, so the list() function allows it to calculate the entire sequence and return a list.

list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘]

Filter in Python:

  

like map (), filter () also receives a function and a sequence. Unlike map (), filter () applies the incoming function to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is true or false.  def  is_odd (n):    return n% 2 = = 1list (filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15 ])#  results: [1, 5, 9, []

Map in JS in map and python

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.