First, Python has two versions, One is python2.x, one is python3.x, the current python3.x more and more popular, these two versions are incompatible, but because I use most of the learning materials are written in python2.x grammar rules, so I collation of the grammar rules are based on python2.x. The part I'm tidying up is basically the place I easily forget.
Data type: Integer (%d), floating-point number (%f), String (str) (%s), Boolean, NULL, variable, constant//and floor, except after or integer. Python also has no size limit for floating-point numbers, but it is represented inf (infinitely large) beyond a certain range.
string and encoding, for the encoding of a single character, Python provides an ord() integer representation of the function to get the character, and the chr() function converts the encoding to the corresponding character
#!/usr/bin/env python3# -*- coding: utf-8 -*-
The second line of comments is to tell the Python interpreter to read the source code according to the UTF-8 encoding, otherwise the Chinese output you write in the source code may be garbled.
Sometimes, % what about a normal character inside a string? This time you need to escape and use it %% to represent a%。
You str bytes need to specify the encoding when and when you convert to each other. The most commonly used encoding is UTF-8 . Python, of course, also supports other encodings, such as encoding Unicode intoGB2312。
One of the data types built into Python is the list: lists. A list is an ordered set of elements that can be added and removed at any time. List is a mutable, ordered table
Another ordered list is called a tuple: a tuple. The tuple and list are very similar, but the tuple cannot be modified once it is initialized.
Python built-in dictionary: dict support, Dict full name dictionary, in other languages also known as map, using key-value (Key-value) storage, with a very fast search speed.
Set is similar to Dict and is a set of keys, but does not store value. Because key cannot be duplicated, there is no duplicate key in set.
*argsis a variable parameter, and args receives a tuple;
**kwis a keyword parameter, kw receives a dict.
And how to pass in the syntax for variable and keyword arguments when calling a function:
Variable parameters can be directly passed func(1, 2, 3) in:, you can first assemble a list or a tuple, and then pass in *args : func(*(1, 2, 3)) ;
Keyword parameters can be directly passed in: func(a=1, b=2) , you can first assemble dict, and then pass in **kw : func(**{‘a‘: 1, ‘b‘: 2}) .
It *args is customary to use and **kw be python, but it is also possible to use other parameter names, but it's best to get used to idioms.
The named keyword parameter is used to limit the name of the parameter that the caller can pass in, as well as providing a default value.
Define a named keyword parameter do not forget to write a delimiter without a mutable parameter * , otherwise the positional parameter will be defined.
Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.
L[0:3]Represents, starting from the index, until the index 0 3 , but not including the index 3 . That is, the index,,, 0 1 2 exactly 3 elements, if the first index is 0 , you can also omit
First 10 numbers, each of two fetch one:
L[:10:2]
All numbers, fetch one per 5:>>> L[::5]
Don't even write anything, just write [:] to copy a list
Use the built-in isinstance function to determine if a variable is a string
So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop computes the mechanism, called the generator: Generator.
There are a number of ways to create a generator. The first approach is simple, as long as you change a list-generated formula [] () to create a generator
If you want to print out one, you can next() get the next return value of generator by function
We have said that generator saves the algorithm, each time it is called next(g) , computes g the value of the next element until the last element is computed, and when there are no more elements, the error is thrown StopIteration .
Of course, this constant invocation is next(g) so perverted that the correct approach is to use for loops, because generator is also an iterative object:
fibThe function is actually the extrapolation rule that defines the Fibonacci sequence, starting with the first element and extrapolating any subsequent elements, which are actually very similar to generator. In other words, the above functions and generator are only a step away. To turn fib a function into a generator, you just need to print(b) change yield b it.
We already know that for there are several types of data that can be directly acting on a loop:
A class is a collection of data types, such as,,, list tuple , and dict set str so on;
One is generator to include the generator and yield the generator function with the band.
These objects, which can be directly acting on for a loop, are called iterative objects:Iterable
Turn list , dict wait, and str Iterable turn into Iterator functions that can be used iter()
You may ask, why, list dict , str etc. data types are not Iterator ?
This is because the Python Iterator object represents a data stream, and the iterator object can be next() called by the function and will return the next data continuously until there is no data to throw an StopIteration error. You can think of this data stream as an ordered sequence, but we can't know the length of the sequence in advance, only by continuously using the next() function to calculate the next data on demand, so Iterator the calculation is lazy, and it will only be calculated when the next data needs to be returned.
IteratorIt can even represent an infinitely large stream of data, such as the whole natural number. Using list is never possible to store all natural numbers.
Let's look at map first. The map() function receives two parameters, one is the function, the other is to function the Iterable map incoming function to each element of the sequence sequentially, and the result is Iterator returned as a new
Again look at reduce the usage. To function reduce on a sequence [x1, x2, x3, ...] , the function must receive two parameters, reduce and the result continues and the next element of the sequence is accumulated, the effect is:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
Python's built-in filter() functions are used to filter the sequence.
and map() similar, filter() also receive a function and a sequence. And the map() difference is that the filter() incoming function acts on each element in turn, and then whether True False the element is persisted or discarded based on the return value.
For example, in a list, delete even numbers, keep only odd numbers, and you can write:
def is_odd(n): return n % 2 == 1list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))# 结果: [1, 5, 9, 15]
Notice that the filter() function returns one, which is Iterator an inert sequence, so to force the result of the filter() calculation, you need to use the function to list() get all the results and return the LIS
by default, the string is sorted by the size of ASCII, because, as a ‘Z‘ < ‘a‘ result, uppercase letters are Z a preceded by lowercase letters.
sorted() The function is also a high-order function, and it can also receive a key function to implement a custom sort, for example, by absolute size
>>> sorted([36, 5, -12, 9, -21], key=abs)[5, 9, -12, -21, 36]
To reverse order, you do not have to change the key function, you can pass in the third argumentreverse=True
Higher-order functions can also return a function as a result value, in addition to the ability to accept functions as parameters.
When we pass in a function, there are times when we don't need to explicitly define a function, and it's easier to pass in an anonymous function directly.
The function object has a __name__ property that can get the name of the function
Now, suppose we want to enhance now() the function of functions, for example, to automatically print the log before and after a function call, but do not want to modify the definition of the now() function, this way of dynamically adding functionality during the run of the code, called "Adorner" (Decorator).
Essentially, decorator is a higher-order function that returns a function. So, we want to define a decorator that can print the log, which can be defined as follows:
def log(func): def wrapper(*args, **kw): print(‘call %s():‘ % func.__name__) return func(*args, **kw) return wrapper
Observe the above log , because it is a decorator, so accept a function as an argument and return a function.
The Python functools module provides a number of useful functions, one of which is the partial function
So, the simple summary functools.partial of the function is to put some parameters of a function fixed (that is, set the default), return a new function, call this new function is more simple.
Notice that the new function above int2 simply base sets the parameter back to the default value 2 , but can also pass in other values when the function is called. This principle can be used when too many parameters require simplification and some values are fixed.
Python itself has many very useful modules that can be used immediately as soon as the installation is complete.
In a module, we may define many functions and variables, but some functions and variables we want to use for others, some functions and variables we want to use only within the module. In Python, this is done by a _ prefix.
Variables such as __xxx__ these are special variables, can be directly referenced, but for special purposes, such as the above __author__ , __name__ is a special variable, hello module-defined document comments can also be accessed with special variables __doc__ , our own variables are generally not used in this variable name.
_xxx __xxx a function or variable like this is nonpublic (private) and should not be directly referenced, such as _abc , __abc etc.
The Python code rules I've compiled