Five unknown advanced features of Python

The high-level features of any programming language are usually discovered through a lot of experience. For example, you are writing a complex project and looking for the answer to a question on stack overflow. Then you suddenly found a very elegant solution that uses Python functions you never knew!

This way of learning is so interesting: discover something by chance through exploration.

Here are five advanced features of Python and their usage.

Lambda function

Lambda function is a relatively small anonymous function -- anonymity means that it actually has no function name.

Python functions usually use def a_function_name() style, but for the lambda function, we don't name it at all. This is because the function of lambda function is to perform some simple expression or operation without completely defining the function.

lambda functions can use any number of arguments, but expressions can only have one.

x = lambda a, b : a * b  
print(x(5, 6)) # prints  30  
x = lambda a : a*3 + 3  
print(x(3)) # prints  12 

Look how simple it is! We perform some simple mathematical operations without defining the entire function. This is one of the many features of Python that make it a clean, simple programming language.

Map function

Map() is a built-in Python function that can apply functions to elements in various data structures, such as lists or dictionaries. This is a very clean and readable way to perform this operation.

'''
No one answers the problems encountered in learning? Xiaobian created a Python exchange of learning QQ Group: 531509025
 Look for like-minded friends to help each other,There are also good videos and tutorials in the group PDF e-book!
'''
def square_it_func(a):  
    return a * a  
x = map(square_it_func, [1, 4, 7])  
print(x) # prints  [1, 16, 47]  
def multiplier_func(a, b):  
    return a * b  
x = map(multiplier_func, [1, 4, 7], [2, 5, 8]) 
print(x) # prints  [2, 20, 56] 

Look at the example above! We can apply functions to single or multiple lists. In fact, you can use any Python function as input to the map function as long as it is compatible with the sequence element you are working on.

Filter function

The filter built-in function is very similar to the map function. It also applies functions to sequence structures (lists, tuples, dictionaries). The key difference between the two is that filter() will only return elements that the application function returns True.

See the following example for details:

# Our numbers  
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]  
# Function that filters out all numbers which are odd  
def filter_odd_numbers(num):  
    if num % 2 == 0:  
        return True  
    else:  
        return False  
filterfiltered_numbers = filter(filter_odd_numbers, numbers)  
print(filtered_numbers)  
# filtered_numbers = [2, 4, 6, 8, 10, 12, 14] 

Not only do we evaluate True or False for each list element, the filter() function also ensures that only elements matching True are returned. It's very easy to handle the two steps of checking expressions and building return lists.

Itertools module

Python's Itertools module is a collection of tools that handle iterators. An iterator is a data type that can be used in for loop statements, including lists, tuples, and dictionaries.

Using the functions in the Itertools module allows you to perform many iterator operations, which usually require multi line functions and complex list understanding. For the magic of Itertools, see the following example:

from itertools import *  
# Easy joining of two lists into a list of tuples  
for i in izip([1, 2, 3], [ a ,  b ,  c ]):  
    print i  
# ( a , 1)  
# ( b , 2)  
# ( c , 3)  
# The count() function returns an interator that   
# produces consecutive integers, forever. This  
# one is great for adding indices next to your list   
# elements for readability and convenience 
for i in izip(count(1), [ Bob ,  Emily ,  Joe ]):  
    print i  
# (1,  Bob )  
# (2,  Emily )  
# (3,  Joe )      
# The dropwhile() function returns an iterator that returns   
# all the elements of the input which come after a certain   
# condition becomes false for the first time.   
def check_for_drop(x):  
    print  Checking:  , x  
    return (x > 5)  
for i in dropwhile(should_drop, [2, 4, 6, 8, 10, 12]):  
    print  Result:  , i  
# Checking: 2  
# Checking: 4  
# Result: 6  
# Result: 8  
# Result: 10  
# Result: 12  
# The groupby() function is great for retrieving bunches  
# of iterator elements which are the same or have similar   
# properties  
a = sorted([1, 2, 1, 3, 2, 1, 2, 3, 4, 5])  
for key, value in groupby(a):  
    print(key, value), end=   )  
# (1, [1, 1, 1])  
# (2, [2, 2, 2])   
# (3, [3, 3])   
# (4, [4])   
# (5, [5])  

Generator function

The Generator function is an iterator like function, that is, it can also be used in a for loop statement. This greatly simplifies your code and saves a lot of memory compared to a simple for loop.

For example, we want to add all the numbers from 1 to 1000. The first part of the following code block shows you how to use the for loop to do this calculation.

If the list is small, such as 1000 rows, the memory required for calculation is OK. But if the list is very long, such as a billion floating-point numbers, this will cause problems. With this for loop, a large number of lists will appear in memory, but not everyone has unlimited RAM to store so many things. The range() function in Python does the same, building lists in memory.

The second part of the code shows how to sum a list of numbers using the Python generator function. The generator function creates elements and stores them in memory only if necessary, one at a time. This means that if you want to create billions of floating-point numbers, you can only store them in memory one at a time! Python 2. The xrange() function in X uses the generator to build the list.

The above example shows that if you want to generate a list for a large range, you need to use the generator function. This is especially important if you have limited memory, such as using mobile devices or edge computing.

That is, if you want to iterate over the list many times and it's small enough to put into memory, it's best to use a for loop or Python 2 Range function in X. Because the generator function and xrange function will generate new list values every time you access them, while Python 2 The X range function is a static list, and integers have been placed in memory for quick access.

'''
No one answers the problems encountered in learning? Xiaobian created a Python exchange of learning QQ Group: 531509025
 Look for like-minded friends to help each other,There are also good videos and tutorials in the group PDF e-book!
'''
# (1) Using a for loopv  
numbers = list()  
for i in range(1000):  
    numbers.append(i+1)  
total = sum(numbers)  
# (2) Using a generator  
 def generate_numbers(n):  
     num, numbers = 1, []  
     while num < n:  
           numbers.append(num)  
     num += 1  
     return numbers  
 total = sum(generate_numbers(1000))  
 # (3) range() vs xrange()  
 total = sum(range(1000 + 1))  
 total = sum(xrange(1000 + 1))  

Keywords: Python Programming

Added by robinhood on Mon, 03 Jan 2022 12:46:26 +0200