A description
filter () function is used to filter sequences, filtered ineligible element returns a list of qualified new elements. The receiving two parameters, as a function of a first, a second sequence, each element of the sequence
as an argument to a function arbitrates, then return True or False, and finally returns True new elements into the list.
Second, the syntax
is the syntax filter () method:
filter(function, iterable)
Parameters: determination function is a function ----
---- is iterables iterable
Return Value:
finally returns a list of
Third, examples
DEF the even (NUM): IF NUM% 2 == 0: return True the else : return False LIS = [1,2,3,4,5,6 ] RES = filter (the even, LIS) Print (List (RES)) # filter retaining only return true data
Output:
[2, 4, 6]
2. Filter all odd list:
def is_odd(n): return n % 2 == 1 newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(list(newlist))
Output:
[1, 3, 5, 7, 9]
3. 1 ~ 100 filtered square root of the number is an integer of:
import math def is_sqr(x): return math.sqrt(x) % 1 == 0 newlist = filter(is_sqr, range(1, 101)) print(list(newlist))
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]