Python filter&sorted

Source: Internet
Author: User

Filter

Filter () 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
In a list, delete the even number, leaving only the odd number:
def is_odd (n):
return n% 2 = = 1
List (filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))


Sorted

The python built-in sorted () function can sort the list:
>>> Sorted ([36, 5,-12, 9,-21])
[-21,-12, 5, 9, 36]

The sorted () function is also a high-order function, and it can also receive a key function to implement a custom sort, such as by absolute size:
>>> sorted ([5, -12, 9, -21], key=abs)
[5, 9,-12,-21, 36]

Use a key function to map a string to ignore case ordering
Reverse sort, without changing the key function, you can pass in the third parameter reverse=true:
>>> sorted ([' Bob ', ' about ', ' Zoo ', ' credits '], Key=str.lower, reverse=true)
[' Zoo ', ' credits ', ' Bob ', ' about ']

Key also accepts a function, which accepts only one element
Reverse: Sorting rules. Reverse = True descending or reverse = False Ascending

Python filter&sorted

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.