SoFunction
Updated on 2024-12-19

Python learning the magic function (filter, map, reduce) details

In today's chapter, we're going to look at three advanced functions in Python, also known as magic functions. The main reason they're so advanced is because most of the data types they return are iterators.

As we saw in the previous section, iterators can improve the execution efficiency of our code and reduce memory consumption. So let's get to know these magic functions.

filter() function

The filter() function is a built-in function of python.

The function of the filter() function: you can take a traversable object and generate an iterator based on the filter criteria. (In python 2.7, it returns a list)

How to use the filter() function:

Usage:

filter(function, list)

Parameter Description:

function: the definition of conditional filtering for each item of the list (mainly on the second parameter of each member of the judgment, to meet the requirements of the function, will enter the iterator generated by the filter)

list: the list to be filtered (not necessarily just lists, but iterable objects)

The demo case is as follows (filter out all even numbers in the list):

def is_even(n):
    return n % 2 == 0


newlist = filter(is_even, [1, 2, 3, 4, 5, 6])
print(newlist, type(newlist))

# >>> The result of the execution is as follows:
# >>> <filter object at 0x7fb241492310> <class 'filter'>

for i in newlist:
    print(i)

# >>> The result of the execution is as follows:
# >>> 2
# >>> 4
# >>> 6

PS: Note that non-even numbers here, although they will be discarded by the filter function, will still exist in the previous list.

map() function

The map() function is a built-in function of python.

The function of the map() function is to execute the function on each member of the list in turn, put the result of the execution into a new list, and return an object corresponding to the map.

How to use the map() function:

Usage:

map(function, list)

Parameter Description:

function: judge the condition of each item of the list.

list: the list to be filtered (not necessarily just a list, but an iterable object)

The demo case is as follows (determining whether each member of the list is greater than 1):

result = map(lambda x: x>1, [0, 1, 2, 3])

print(result, type(result))

# >>> The result of the execution is as follows:
# >>> <map object at 0x7facfa399e80> <class 'map'>

for i in result:
    print(i)
    
# >>> The result of the execution is as follows:
# >>> False
# >>> False
# >>> True
# >>> True

The reduce() function

The reduce() function used to be a built-in function of python, but not anymore. (In the python version, the reduce() function could be called directly; however, in the python version, since it returns something other than an iterator, you need to perform an import before you can continue using it. import statement from functools import reduce)

The function of the reduce() function is to add or multiply two pieces of data before and after the loop. (You can actually do anything you want with these two members via lambda)

How to use the reduce() function:

Usage:

reduce(function, list)

Parameter Description:

function: a function that accumulates/accumulates data.

list: the list to be filtered (not necessarily just lists, but iterable objects)

The demo case is as follows (adding or multiplying the two data before and after the loop):

from functools import reduce

result = reduce(lambda x, y: x + y, [1, 2, 3])

print(result, '---', type(result))

# >>> The result of the execution is as follows:
# >>> 6 --- <class 'int'>


from functools import reduce


result = reduce(lambda x, y: x * y, [1, 3, 5])

print(result, '---', type(result))

# >>> The result of the execution is as follows:
# >>> 15 --- <class 'int'>

filter() function

scores = [("Zhang San", 89, 90, 59),
          ("Li Si.", 99, 49, 59),
          ("Zhao Wu", 99, 60, 20),
          ("Wang Ermazi", 40, 94, 59),
          ("Lee Ray.", 89, 90, 59),
          ("Lilly.", 89, 90, 69),
          ("Chu Xie.", 79, 90, 59),
          ("Neo", 85, 90, 59),
          ("Abby", 89, 91, 90)]

def handle_filter(a):
    s = sorted(a[1:])   # Ranking of three subject scores
    
    # 2 subjects with a score of 80 or higher and 1 subject with a score of less than 60
    if s[-2] > 80 and s[0] < 60:
        return True
    
    # 1 subject with a score of 90 or above and 2 other subjects with a score of 60 or below
    if s[-1] > 90 and s[1] < 60:
        return True
    if s[-2] > 80 and sum(s)/len(s) < 60:
    
    # 1 subject with a score of 90 or above and 3 subjects with an average score of 70 or below
        return True
    return False


newIter = list(filter(handle_filter, scores))
print(newIter)

# >>> The result of the execution is as follows:
# >> [('Zhang San', 89, 90, 59), ('Li Si', 99, 49, 59), ('Wang Ermazi', 40, 94, 59), ('Li Lei', 89, 90, 59), ('Neo', 85, 90, 59)]

To this point this article on Python learning magic function (filter, map, reduce) detailed article is introduced to this, more related Python filter() map() reduce() content please search my previous posts or continue to browse the following related articles I hope that you will support me in the future more!