Built-in functions - filter and map

  Built-in functions - filter and map

  filter

The filter() function accepts a function f and a list. The function of this function f is to judge each element and return True or False. According to the judgment result, filter() automatically filters out the elements that do not meet the conditions, and returns the elements that meet the conditions. A new list composed.

For example, to remove even numbers from a list[1,4,5,2,5,12] and keep odd numbers, first, write a function to determine odd numbers:
def is_odd(x):
return x % 2 == 1
then , use filter() to filter out even numbers:
filter(is_odd, [1, 4, 6, 7, 9, 12, 17])
Output:
[1, 7, 9, 17]


With filter(), many useful things can be done Function, for example, to remove None or empty strings:
def is_not(s):
return s and len(s.strip()) >0
pr = filter(is_not, ['test', None, '', 'str', ' ', 'END'])

print(list(pr))

Output:
['test', 'str', 'END']


Note: s.strip(rm) removes the characters of the rm sequence at the beginning and end of the s string.

When rm is empty, whitespace characters (including '\n', '\r', '\t', ' ') are deleted by default,
as follows:

>>> a = ' 123'
>>> a.strip()
'123'

>>> a = '\t\t123\r\n'
>>> a.strip()
'123'

  practise:

Please use filter() to filter out the number whose square root is an integer from 1 to 100, that is, the result should be:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

  method:


import math
def is_sqr(x):
return math.sqrt(x) % 1 == 0
print filter(is_sqr, range(1, 101))

Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

map


The map function in Python is applied to each item in an iterable and returns a list of results. If other iterable parameters are passed in, the map function will iterate through each parameter with the corresponding processing function. The map() function receives two parameters, one is a function and the other is a sequence, map applies the incoming function to each element of the sequence in turn, and returns the result as a new list.

There is a list, L=[1,2,3,4,5,6,7,8], we want to apply f(x)=x^2 to this list, then we can use the map function to process

>>> L = [1,2,3,4,]
>>> def pow2(x):
... return x*x
...
>>> map(pow2,L)
[1, 4, 9, 16]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324903229&siteId=291194637