Concise built-in functions

Hello, I’m back, and today I want to share with you some of Python’s most important built-in functions: Map, Filter, Reduce, zip. The main use is for processing sequences. We can use them to apply little functions to all the elements of a sequence. This saves time writing explicit loops.

In addition, map, filter, reduce, and zip are pure functions that return values. So we can easily express the return result of a function as an expression.

My personal understanding is that by using them, we can simplify our code to perform tasks that require iteration more succinct and efficiently. Here are some examples

map()

The function structure

The map() function is used to execute a method on an iterable sequence, such as a List, as follows:

  • Map (fun, iterable)
  • Argument: Fun is a map function that passes each element of a given iterable sequence. Iterable is an iterable sequence in which each element can perform fun
  • Returned value: Map Object

We can execute fun on each element of the sequence iterable using map mapping

Basic usage:

Let’s look at a small example. Suppose we have a List of five numbers, from 1 to 5, and we want to increase each number by 1. If we didn’t know about map, our solution would look like this:

Numbers = [1, 2, 3, 4] print(numbers) Out:[2, 3, 4, 5] print(numbers) Out:[2, 3, 4, 5] print(numbers) Out:[2, 3, 4, 5]Copy the code

Or something like this:

numbers = [1, 2, 3, 4, 5]
result = []
for n in numbers:
    result.append(n+1)
print(result)
Out:[2, 3, 4, 5, 6]
Copy the code

It’s better to use a list expression here, which I’ll summarize in a later article

But obviously, writing loops are involved either way, and this is where the map function comes in. We can use the map function to do this:

def add_one(n):
    return n + 1

numbers = [1, 2, 3, 4, 5]
result = map(add_one, numbers)
print(result)
print(type(result))
print(list(result))

Out:<map object at 0x00000260F508BE80>
    <class 'map'>
    [2, 3, 4, 5, 6]
Copy the code

Here we see the benefits of map. While simplifying the code, we can somewhat separate the methods from the loop. Here we see that the map returns the Map class, the sequence we pass is a List, and the final output is also a List after typecasting

As long as the sequence is iterable when passing it, it doesn’t have to be a List. Let’s say instead:

def add_one(n): Result = map(add_one, numbers) print(tuple(result)) # Out :(2, 3, 4, 5) # Out :(2, 3, 4, 5)Copy the code

The input sequence is the same iterable tuple, and the output sequence is the same tuple.

Now to optimize, use the previous example again. For brevity, let’s use the lambda function with map:

numbers = (1, 2, 3, 4, 5)                     The iterated object is tuple
result = map(lambda x: x + 1, numbers)
print(list(result))                           The output object is listOut: [2, 3, 4, 5, 6]Copy the code

More concise and elegant right!! The lambda function, which I’ll talk about later, is not the main character today, but I’ll pass it on. Moving back to map, there is one other situation that is quite common, such as the following example:

# List of strings
words = ['paris'.'xiaobai'.'love']

Change each element of the array to a List
test = list(map(list, words))
print(test)

Out: [['p'.'a'.'r'.'i'.'s'], ['x'.'i'.'a'.'o'.'b'.'a'.'i'], ['l'.'o'.'v'.'e']]
Copy the code

Words is a list containing only string elements. We can use map to convert each element of words into a list. Note that this can be achieved only if each element is an iterable type.

# List of strings
words = [18,'paris'.'xiaobai'.'love']

Change each element of the array to a List
test = list(map(list, words))
print(test) Out: TypeError:'int' object is not iterable

Copy the code

So the correct way to use it must be something like this:

nums = [3,"23",-2]
print(list(map(float,nums)) Out: [3.0, 23.0, -2.0]Copy the code

All in all, pay attention to the type, I just introduced a simple map, you can develop the specific usage of ha, I also continue to learn

filter()

The function structure

The filter () method filters a given sequence with the help of a function that tests whether each element in the sequence is true.

  • Basic syntax: filter(fun, iterable)
  • Arguments: Fun tests True for each element in an iterable sequence that is filtered and iterable
  • Return value: an iterable sequence containing elements that are True for fun

In short, filter can help us filter a set of data according to given conditions and return results

Basic usage:

Let’s start with an example:

Def fun(variable): letters = ['a', 'e', 'I ', 'o', 'u'] if (variable in letters): return True else: def fun(variable in letters): return True else: Return False # given sequence sequence = [' I ', 'l', 'o', 'v', 'e', 'p', 'y', 't', 'h', 'o', 'n'] # according to the condition results filtered = list (filter (fun, sequence)) print (filtered) Out: [' o ', 'e', 'o']Copy the code

Here we create a method called fun to extract vowels. Given the iterable sequence list, we can easily extract vowels using filter.

# is positive
def positive(num):
    if num>0:
        return True
    else:
        return False

# Determine even numbers
def even(num):
    if num % 2==0:
        return True
    else:
        returnPositive_nums = list(filter(positive, numbers))print(positive_nums)  Print a positive list


even_nums = tuple(filter(even,numbers))
print(even_nums)     Print an even number of tuplesOut: [1, 5, 9, 12] (-20, 0, 12)Copy the code

The basic usage of filter is to have a method that returns True or False, or an expression as a filter condition

further

This is the same as map, but basically the simplest way to use it is to mix it up with a lambda. For example, we want to compress the code we just wrote:

numbers = [0, 1, 2, -3, 5, -8, 13]

# extract odd number
result = filter(lambda x: x % 2, numbers)
print("Odd Numbers are :",list(result))

# extract even numbers
result = filter(lambda x: x % 2 == 0, numbers)
print("Even Numbers are :",list(result))

Extract a positive number
result = filter(lambda x: x>0, numbers)
print("Positive Numbers are :",list(result) Out: Odd Numbers are: [1, -3, 5, 13] Even Numbers are: [0, 2, -8] Positive Numbers are: [1, 2, 5, 13]Copy the code

“Cool! Cool!” After seeing this, Guo degang commented, “I don’t usually use lambda very much, but using lambda here can just reflect one of python’s concepts: efficient and concise!

reduce()

The function structure

Reduce is a very useful function for performing some computation on a list and returning the result. It applies scrolling calculations to successive values in a list. For example, if you want to compute a cumulative multiplication of a list of integers, or a sum, etc

  • Reduce (function, iterable)
  • Arguments: Fun is a method that continuously applies to each element of iterable. The new arguments are the result of the last execution and iterable is a filtered iterable sequence
  • Return value: The final function returns the result

In Python 2, reduce () is a built-in function. In Python 3, however, it was moved to the FuncTools module. Therefore, we need to import it before we can use it, and here my environment is Python 3.6

Basic usage:

Let’s start with a little chestnut:

from functools import reduce # Python 3

def do_sum(x1, x2): 
    return x1 + x2
    
printReduce (do_sum, [1, 2, 3, 4])) Out: 10Copy the code

Here’s another example of cumulative multiplication:

from functools import reduce # Python 3
def multiply(x, y):
    returnX * y Numbers = [1, 2, 3, 4]printMultiply (multiply, numbers) Out: 24Copy the code

One step further:

Again, it’s a little more succinct to mix and match lambda:

from functools import reduce # Python 3Numbers = [1,2,3,4] result_multiply = reduce((lambda x,y: x * y), numbers) result_add = reduce((lambda x,y: x * y) x+y), numbers)print(result_multiply)
printResult_add) Out: 24 10Copy the code

zip()

The function structure

The purpose of zip () is to map similar indexes of multiple containers so that they can be used only as a single entity.

  • Basic syntax: zip(*iterators)
  • Parameters: Iterators are iterable objects, such as list and string
  • Return value: Returns a single iterator object with mapped values from all containers

Basic usage:

We actually mentioned it earlier when we talked about how to create dict, but here’s a review:


keys = ['name'.'age']
values = ['xiaobai',18]
my_dict = dict(zip(keys,values))
print(my_dict) Out: {'name': 'xiaobai'.'age'18} :Copy the code

Zip can support multiple objects, such as the following example

name = [ "xiaobai"."john"."mike"."alpha" ]
age = [ 4, 1, 3, 2 ]
marks = [ 40, 50, 60, 70 ]

# using zip() to map values
mapped = list(zip(name, age, marks))
print ("The zipped result is : "The zipped result is: [('xiaobai', 4, (40),'john', 1, 50), ('mike', 3, (60),'alpha', 2, 70)]

Copy the code

Here we can easily package the name, age, and marks lists with the same index mapping

One step further:

From the above example, we found that it is very easy to pack the values of the same index position of different objects in a form similar to 1-to-1. What about unpacking? It’s the same thing, just with an extra star

names, ages, marks = zip(*mapped)
print ("The name list is : ",names)
print ("The age list is : ",ages)
print ("The marks list is : ",marks) Out: The name list is:'xiaobai'.'john'.'mike'.'alpha')
     The age list is :  (4, 1, 3, 2)
     The marks list is :  (40, 50, 60, 70)
Copy the code

conclusion

Today is mainly to introduce the map, filter, reduce, zip four efficient python built-in function usage, I also just contact, understanding is not enough in-depth, if you have any mistakes or introduction of ambiguity also please great understanding and tolerance, if there is a great god can be further added must write a comment, let us progress together.