12. Filter

Source: Internet
Author: User

Python's built-in filter() functions are used to filter the sequence.

and map() similar, filter() also receive a function and a sequence. And the map() difference is that the filter() incoming function acts on each element in turn, and then whether True False the element is persisted or discarded based on the return value.

For example, in a list, delete even numbers, keep only odd numbers, and you can write:

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

To delete an empty string from a sequence, you can write:

def Not_empty (s):     return  and S.strip () List (filter (Not_empty, ['A'"') 'B ' ' C ' '  ' ])#  results: [' A ', ' B ', ' C ']

filter()the key to using this higher-order function is to implement a "filter" function correctly.

Notice that the filter() function returns one, which is Iterator an inert sequence, so to force the result of the filter() calculation, you need to use the list() function to get all the results and return to the list.

# Coding=utf-8   def is_palindrome (n):     return str (n) = = str (n) [::-1 = Filter (Is_palindrome, Range (1,))print (list (output))

Small summary, the use of slices [::-1] The reverse sequence of slices, range lists the certificate sequence within the specified range

SortedSorting algorithms

Sorting is also an algorithm that is often used in programs. Whether you use bubble sorting or fast sorting, the core of the sort is to compare the size of the two elements. If it is a number, we can compare it directly, but what if it is a string or two dict? There is no point in directly comparing the size of mathematics, so the process of comparison must be abstracted by functions.

12. Filter

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.