python Basics

python Basics

Following the previous [python foundation]

Explain:

  • Refer to the series of documents added to the official website: python 3.7
  • Each part of the code is written to second.py in the same file
  • Declared variables are public.

The last one is mainly introduction. If you have learned other programming languages, you can understand it by basic hands-on operation.

Advanced features

Section
The operation method of getting partial data (similar to slice).

Explain:

  • The basic syntax represents [start:end], the actual position of start and the end position (excluding); it accepts a negative number (- 1), starting from the last element.
  • The default start is 0, and the default end is data length.
  • [start:end:sep] indicates that the interval sep takes a value;
# [:] generate 10 ordered sequences
names = list(range(11))
print(names[1:6])
# [::]
print(names[1:6:2])

iteration

for...in to iterate data;

Explain:

  • Import the Iterable type through the collections.abc module
  • isinstance determines whether the data type is the same as the given type, and returns bool.
  • The list is converted to an index element pair through the built-in function enumerate.
# Judge whether the current data can be iterated
from collections.abc import Iterable
# output True
print(isinstance(names,Iterable))
# enumerate
names = enumerate(names)
for k,v in names:
    print(k,v)

List generation

Generate data quickly. Operation in [] expression;

Explain:

  • The for loop takes the variable.
# [] simple expression
nums = [n*n for n in [2,4,8]]
print(nums)
# Multilayer operation
nums = [n*m for n in [2,4,8] for m in [1,3,6]]
print(nums)

generator

Generator function can be used to generate data. It is not necessary to list all data to reduce the space occupied by data.

Explain:

  • () create a generator;
  • next() is used to get the element. When the last element is obtained, the error StopIteration will be reported when getting it again.
  • Use the yield keyword in ordinary functions to become a generator function;
# generator
names=(n*n for n in [2,4,8])
for val in names:
    print("for-",val)
# The for loop has output all values, and an error is reported when calling next().
print(next(names))

iterator

  iteration object Iterator represents data flow and can only access the next value through next() method; basic data type list/dict/set is iterative data, but not iterative object.

Explain:

  • isinstance() determines whether it is an iterative object.
  • By using the iter() function, the iteratable data is transformed into iterated objects.
  • Generators can be used to generate infinite data streams.
# Determine whether the current data type is an iterative object
from collections.abc import Iterator
# False
print(isinstance(nums,Iterator))
# True
print(isinstance(names,Iterator))
# using iter()    output: True
print(isinstance(iter(nums),Iterator))

function

Learning is based on the front-end basis. Some syntax and semantics similar to JS will not be written repeatedly, only the differences will be recorded.

Anonymous function

Explain:

  • lambda represents anonymous function.
# Anonymous function
total = lambda val:val*3
# 12
print(total(4))

Decorator

The way to dynamically add functions during code running is called decorator

Explain:

  • __The name property returns the name of the function definition
  • @Indicates the name of the function that needs to be executed additionally, which is called automatically.
  • The decorator takes the current function as an argument for callback execution.
  • @functools.warps() is used to copy the properties of the original function to the return function, such as the wrapper function in the instance, which causes the name to become the wrapper.
# Decorator @ + function name
def log(fn):
    def wrapper(*arg,**oth):
        print("------operation--------",fn.__name__,"---------Operation user name---------",arg[0])
        return fn(*arg,**oth)
    return wrapper
@log
def login(user):
    print("Welcome landing:"+user)
    
# ------Operation -------- login -------- operation user name -------- admin
# Welcome to: admin
login("admin")
# Adding custom parameters to decorator functions
import functools

def log(bool):
    def decorator(fn):
            @functools.wraps(fn)
        def wrapper(*arg,**oth):
            print("------operation--------",fn.__name__,"---------Operation user name---------",arg[0])
            if bool:
                print("2019-10-06")
            return fn(*arg,**oth)
        return wrapper
    return decorator
@log(True)
def login(user):
    print("Welcome landing:"+user)
# ------Operation -------- login -------- operation user name -------- test
# 2019-10-06
# Welcome to: test
login("test")

Partial function

With functools.partial(), you can set the default value parameters of a defined function.

Explain:

  • To set the common function, each module needs to pass its own identification for different processing operations.
  • functools.partial() second parameter if no parameter name is specified, such as flag=False, the parameter will be put to arg[0] first by default.
# Set function defaults
def info(name,flag = True):
    adorn = ""
    if flag:
        adorn = "Honourable"
    print("Welcome"+adorn+"Guest:",name)

info("admin",False)
info("test",False)
# Set the processing through functools.partial() without passing the parameter flag every time
info_ = functools.partial(info,flag=False)
info_("admin")
info_("test")

Modular

Divide by function and package the modules written by each person. Prevent naming conflicts

Explain:

  • from...import... Import methods or variables in a module
  • import... Imports the entire module, using the
  • The package with directory as package must contain the file "init. Py", which can be empty.

Example package directory:

# Module usage
# Import a method or variable from a module file
from logs.info import print_log
# Import the whole module user.info call get when using
import user.info

print_log()
print(user.info._Author_)

regular expression

The re module contains all the functions of regular expressions.

Explain

  • Use r '' when using due to escape of string itself \
  • match object returned when re.match() matches
  • The first parameter of re.split() provides regular expression, split string, and the data type is list.
  • group() gets the matching result only, and group(0) is always the original string.
  • groups() returns the matching result value (tuple)
  • re.compile() uses precompiled regular expressions. During subsequent use, the program will no longer compile
# re module regular expression
import re

# Match any character once or more +'lo '
print(re.match(r".+lo","hello"))
# Match 'l' one or more times to split
print(re.split(r"l+","hello"))

# groups         ('h', 'lo')
print(re.match(r"^([a-z]+)el([a-z]+)$","hello").groups())
# Compile expressions and,
reg_ = re.compile(r"\d+\+\d+");
print(reg.match("2233+123").group(1))

This article is based on the platform of blog one article multiple sending OpenWrite Release!

Keywords: Python Lambda Programming

Added by wpsd2006 on Wed, 23 Oct 2019 06:13:54 +0300