How to Use map, reduce, filter, and sorted functions in Python, pythonsorted

Source: Internet
Author: User

How to Use map, reduce, filter, and sorted functions in Python, pythonsorted

Map

map(funcname, list)

The python map function allows the function to pass each element of the list directly to funcname as a parameter and return a new list in the response.
As follows:

Def sq (x): return x * x # evaluate the square map (sq, [, 9]) of x # [1, 9, 25, 49, 81]

It is convenient to convert each element in the list.

For example, convert each int in the list to str

map(str, [23,43,4545,324]) #['23', '43', '4545', '324']

Of course, the second parameter is list, which can be tuple or set list structure. dict cannot, but the returned result is list.

map(sq, (1,3, 5,7,9)) # tuple [1, 9, 25, 49, 81]map(sq, set([1,3, 5,3,7,9])) # set [1, 9, 81, 25, 49]

By the way, the dict structure is represented by {}, as shown in figure

 {"name": "Yi_Zhi_Yu", "age":25}

Is an intuitive key-value form. If {} contains a list-like structure, for example:

{"Yi_Zhi_Yu", 25}

In fact, this is the final return form of the set, which is equivalent:

Set (["Yi_Zhi_Yu", 25]) # The final output format is {25, 'yi _ Zhi_Yu '}

In this case, {} will remove duplicates when there are duplicates.

  {1,3, 5, 3, 7, 9} #{1, 3, 5, 7, 9}

Reduce

reduce(funcname, list)

Compared with map, reduce is similar to an application method of an aggregation class. Parameters in the list are passed to funcname in sequence. Each funcname parameter is the execution result of the previous funcname and the element in the next list, therefore, the funcname parameter must be two. the execution process is a bit like recursion.

For example, calculate the sum of range (1,101) (excluding 101,

def c_sum(x, y):  return x + y;reduce(c_sum, range(1,101)) #5050

Filter

filter(funcname, list)

The execution process passes the elements in the list to the funcname function sequentially, and the elements are retained or discarded based on the True or False returned by funcname.

For example, return all int data in a list.

 def is_int(x):  if isinstance(x, (int)):    return True  else:    return False filter(is_int, ["Yi",2, "3", 4]) #[2, 4]sortedsorted( list, [comp_func])

Sorting method. The second parameter is an optional parameter. The result is sorted based on the value returned by the optional parameter. comp_func accepts two parameters (x, y), and the final returned result is-1.0, 1, if-1 is returned, x <y, 0 indicates x = y, and 1 indicates x> y. Therefore, the actual sorting can be customized.
The default value is positive order:

sorted([3,4, 12, 5, 9, 1]) #[1, 3, 4, 5, 9, 12]

If you want to arrange them in reverse order, use the following custom method:

 def m_order(x, y):  if(x > y):    return -1  elif(x == y):    return 0  else:    return 1sorted([3,4, 12, 5, 9, 1], m_order) #[12, 9, 5, 4, 3, 1]

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.