Python notes-----higher-order functions

Source: Internet
Author: User

1, sorted (sort object, key=): The Sort object can be a category, or a string and a dictionary, key is a custom sort, such as: "Key=abs, sorted by absolute value" "Key=lambda x:x[1", sorted by the second value of the sorted object, if it is a two-dimensional array, The second dimension row, if the dictionary is ranked by the value "

①sorted (Sort object, Key=abs):

Value:key=abs "Sort by absolute value"

String: The default is to sort by lowercase to uppercase. key=str.lower"turn all strings into lowercase and reorder" eg:sorted ([' A ', ' dob ', ' Cold ', Zoo '], key=str.lower) Result: ' A ', ' Cold ', ' DOB ', ' Zoo ' "

Dictionary type (two-dimensional array): Fromoperator import Itemgetter

             Key=itemgetter (1)

             Or

Key=lambda X:x[1]

②sorted (Sort object, reverse=true): reverse order

2. Map (function, iterator): Perform the same function operation on an iterator.

Such as:

List (map (str,[1,2,3,4,5))

Result: "' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 '" so you don't have to use for to loop through.

3. Reduce (function, iterator): Iterate over each element in an iterator, such as SUM, Maximum minimum .....

4. Map and reduce combine to convert a string ' 13579 ' into an integer 13579

 from Import reducea=reduce (lambda x,y:x*10+y,map (int,'13579'))

5, filter (function f, iterator L): Filter function, the value returned after the function f is true or has a value is returned, if False or empty does not return the value.

def is_odd (n):     return n% 2 = = 1list (filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))

  

Python notes-----higher-order functions

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.