This is the 19th day of my participation in the August Wenwen Challenge.More challenges in August

📖 preface

Sanmao once sighed:

“What is the mind like? There is a labyrinth that stretches thousands of miles across. There is no boat that can ferry people. Throughout life, we are learning how to be our own ferrymen.

You can watch this blogger’s article about installation and LocalizationVsCode download, Installation and LocalizationAs well asPython series: windows10 configuration Python3.0 development environment!After installation, restart VsCode!


On! What is a higher-order function?

Higher-order functions: a function can be passed as an argument to another function, or a function can return another function (recursion if the return value is the function itself), or a higher-order function if either of them is met.

Parameters are functions

"@descripttion: This is a header comment! @version: 1.0.0 @company: dcit-sh@author: Sunny Chen @date: 2019-10-15 13:42:21 @lasteditors: Sunny Chen @LastEditTime: 2019-10-15 13:42:21 '''

The argument is a function
def chen() :
    print("in the chen..")
def jia(func) :
    func()
    print("in the jia..")

jia(chen)
Copy the code

The return value is function

"@descripttion: This is a header comment! @version: 1.0.0 @company: dcit-sh@author: Sunny Chen @date: 2019-10-15 13:42:21 @lasteditors: Sunny Chen @LastEditTime: 2019-10-15 13:42:21 '''

The return value is a function
def chen() :
    print("in the chen..")
def jia(func) :
    print("in the jia..")
    return bar
res=jia(chen)
res()
Copy the code

In both examples, the function jia() is a higher-order function. In Example 1, the function bar is passed in as an argument to JIA, and in Example 2, the function bar is the return value of JIA.

Note: The function name (e.g. Chen, jia) –> is the memory address of the function; Function name + parentheses (for example Chen (), jia())–> call the function.


Higher-order functions – Map, filter, and Reduce

All three are higher-order functions, which are also built into Python. Let’s take a look at how these three functions are used and how they work internally:

The map function

The map function takes two arguments, a function and a sequence, and returns the sequence of values to the list.

Mechanism of map function:

"@descripttion: This is a header comment! @version: 1.0.0 @company: dcit-sh@author: Sunny Chen @date: 2019-10-15 13:42:21 @lasteditors: Sunny Chen @LastEditTime: 2019-10-16 16:08:25 '''

num=[1.2.3.4.5]
def square(x) :
    return x**2
#map function simulation
def map_test(func,iter) :
    num_1=[]
    for i in iter:
        ret=func(i)
        # print(ret)
        num_1.append(ret)
    return num_1.__iter__() Turn the list into an iterator object

# map_test function
print(list(map_test(square,num)))
# the map function
print(list(map(square,num)))

Map function parameter 1 can also be an anonymous function, and parameter 2 can also be a string
print(list(map_test(lambda x:x.upper(),"Sunny Chen")))
print(list(map(lambda x:x.upper(),"Sunny Chen")))

# output:
# [1, 4, 9, 16, 25]
# [1, 4, 9, 16, 25]
# ['S', 'U', 'N', 'N', 'Y', ' ', 'C', 'H', 'E', 'N']
# ['S', 'U', 'N', 'N', 'Y', ' ', 'C', 'H', 'E', 'N']
Copy the code
The filter function

The filter function is also a higher-order function that receives a function and a sequence, and its main function is filtering. The return value is also an iterator object:

Use of the filter function and its mechanism:

"@descripttion: This is a header comment! @version: 1.0.0 @company: dcit-sh@author: Sunny Chen @date: 2019-10-15 13:42:21 @lasteditors: Sunny Chen @LastEditTime: 2019-10-16 16:12:42 '''

names=["Chen"."Sunny"."xiaojai"]
#filter function mechanism
def filter_test(func,iter) :
    names_1=[]
    for i in iter:
        if func(i): The func function passed in must be a bool to be meaningful
            names_1.append(i)
    return names_1
# filter_test function
print(filter_test(lambda x:x.islower(),names))
# the filter function
print(list(filter(lambda x:x.islower(),names)))

# output:
# ['xiaojai']
# ['xiaojai']
Copy the code
The reduce function

Reduce function is also a function with parameters, a high-order function with an iterable object, and its return value is a value rather than an iterator object. Therefore, it is commonly used in superposition and multiplication, etc., as shown in the following figure:

"@descripttion: This is a header comment! @version: 1.0.0 @company: dcit-sh@author: Sunny Chen @date: 2019-10-15 13:42:21 @lasteditors: Sunny Chen @LastEditTime: 2019-10-15 13:42:21 '''

The #reduce function is not a built-in function, but a function in the module funcTools, so it needs to be imported
from functools import reduce

nums=[1.2.3.4.5.6]
# Reduce function mechanism
def reduce_test(func,array,ini=None) : #ini as the base
    if ini == None:
        ret =array.pop(0)
    else:
        ret=ini
    for i in array:
        ret=func(ret,i)
    return ret
#reduce_test function, multiply
print(reduce_test(lambda x,y:x*y,nums,100))
#reduce, multiply
print(reduce(lambda x,y:x*y,nums,100))

# output:
# 72000
# 72000
Copy the code

On! An introduction to modules

Module definition:

In the development process of computer program, as the program code is written more and more, the code in a file will be longer and longer, will appear more and more disorderly, so that the maintenance of the code is worse and worse. For example, when analyzing the population change of each city in China, if we put the population analysis of each city in a Word document, wouldn’t it be difficult to find the population change of a certain city? Therefore, we can write the analysis of a city in a file, so that it is much easier to find the data analysis of a city. In this case, we put the code for different purposes in different.py files for different functions. The benefits of this are as follows:

  • First, greatly improve the maintainability of the code.
  • Second, open source. You don’t have to write code from scratch. When a module is written, it can be referenced elsewhere. When we write programs, we often refer to other modules, both built-in Python modules and modules from third parties.
  • Using modules can avoid variable and function name conflicts.

A.py file is a module.

Classification of modules:

There are generally three types of modules:

  1. Python standard library, such as time, random, JSON, and other modules

  2. For example: Pandas (python) is a data analysis platform implemented in python.

  3. Custom modules. It’s a self-written.py file


Module import

Import statement

  • Import module1[, module2[,… moduleN] : Directly import modules. This method can be used to import modules in the local directory or built-in modules.
  • How does the Python interpreter find the corresponding file when we use the import statement?
  • The interpreter has its own search path, which can be found by importing the sys module and calling sys.path. When a module is imported using import, it is searched according to the search path. Therefore, if the imported module file is in these search paths, you can directly import it using import. Such as:
  • [‘/usr/lib/python3.6 python_learning/my_module ‘, ‘/ usr/lib/python3.6’, ‘/ usr/lib/python3.6 platt – x86_64 – Linux – gnu’, ‘/ usr/li B/python3.6 / lib – dynload ‘, ‘/ usr/local/lib/python3.6 / dist – packages’,’/usr/lib/python3 / dist – packages’], if the module is in the path, You can use the import method directly.

Second, the from… The import statement

  • From module_name Import name1[, name2[,… nameN]], and import functions or variables in the module.
  • This import method does not import the entire module_name module into the current namespace. Import only specified functions (functions are variables) or variables, etc.
  • *While the from module_name import.Import all functions and variables under module_name.
  • Note: This method is not recommended, because the imported function or variable name may conflict with the function or variable name in this file.

Package (package)

Or the example above, if the data analysis of the population of each city, even if the population of a city will analyze on a Word document, due to so many cities in China, so we can according to the province, can create folders according to the province, the data analysis of the city within the province into the folder. The same is true for packages, except that packages are folders with __init__.py.

Package benefits:

  • â‘  Even if the module name is the same in different packages, it is not affected. In many cases, we often create the same file name in different packages.
  • (2) Files can be classified according to different functions of modules, so the existence of packages can make the classification of files more clear, and make the location of code more clear.

Note: Each time a package is called, the package’s __init__.py file is executed.

For example, my_module and module_test are packages, which must have an __init__.py file.

Import files in package (need to master the first two.)


if __name__ ="__main__"The use of the

If we were to execute something directlyThe lead-in fileWhen the file is so"__name__ = =" __main__ '“It isTrueBut if we go from anotherThe lead-in fileWhen importing the file through import, the __name__ value is the name of the py file instead of __main__.

Therefore,if __name__ = "__main__"Features:

  • Can be used for debugging in imported modules (in imported modulesIf __name__ ="__main__" : -->True), which is not executed when the module is imported (in the import module file, executed when the module is imported)If __name__ = "__main__" : -->Flase).
  • For interface files(bin)The use ofIf __name__ ="__main__" : mian. Run ()Tell someone that you can call my module but not modify it.
"@descripttion: This is a header comment! @version: 1.0.0 @company: dcit-sh@author: Sunny Chen @date: 2019-10-15 13:42:21 @lasteditors: Sunny Chen @LastEditTime: 2019-10-16 16:34:48 '''

#----- is in the cal.py file under the web1.web2.web3 package
def add(x,y) : # addition
    return x+y
def multi(x,y) : # multiplication
    return x*y
# Debug functions in the cal.py file
if __name__ = "__mian__":
    m = add(3.2)
    print(m) 
The output is __main__

#----- is in the web_test.py file that imports the module
from web1.web2.web3 import cal
print( __name__)
# web1.web2.web3.cal

# Do not execute cal.py under if __name__:"__main__" in web_test.py.
Copy the code

Go and try it!

🎉 finally

  • For more references, see here:Chen Yongjia’s blog

  • Like the small partner of the blogger can add a concern, a thumbs-up oh, continue to update hey hey!