Elder martial brother Ali carefully sorted it out Python Relevant basic knowledge , For interview , Or review at ordinary times , It's all very good ! I don't say much nonsense , Directly
Because the article is too long , Xiaobian also sorted the article into PDF file , If you want to watch and learn more conveniently, check the acquisition method at the end of the article ~
Python The language is easy to understand , The easier , With AI Trend , More and more fire
Compiler language : Compile all the good source programs into binary runnable programs . then , You can run this program directly . Such as :C,C++ Explanatory language : Translate a good source program into , Then execute a sentence , Until the end ! Such as :Python, (Java Something special ,java Programs also need to be compiled , But there is no direct compilation called machine language , Instead, the compilation is called bytecode , Then execute bytecode in an interpretive way .)
character string (str): A string is any text enclosed in quotation marks , Is the most commonly used data type in programming languages . list (list): A list is an ordered collection , You can add or remove elements to it . Tuples (tuple): Tuples are also ordered sets , But it cannot be modified . That is, tuples are immutable . Dictionaries (dict): Dictionaries are unordered collections , By key-value Composed of . aggregate (set): It's a group. key Set , Each element is unique , Not repeated and disordered .
character string :
output luobodazahui-good
mystr5 = 'luobo,dazahui good'
# Split by space
print(mystr5.split())
# With h Division
print(mystr5.split('h'))
# Comma separated
print(mystr5.split(','))
output
['luobo,dazahui', 'good']
['luobo,daza', 'ui good']
['luobo', 'dazahui good']
list :
mylist1 = [1, 2]
mylist2 = [3, 4]
mylist3 = [1, 2]
mylist1.append(mylist2)
print(mylist1)
mylist3.extend(mylist2)
print(mylist3)
outout
[1, 2, [3, 4]]
[1, 2, 3, 4]
mylist4 = ['a', 'b', 'c', 'd']
del mylist4[0]
print(mylist4)
mylist4.pop()
print(mylist4)
mylist4.remove('c')
print(mylist4)
output
['b', 'c', 'd']
['b', 'c']
['b']
mylist5 = [1, 5, 2, 3, 4]
mylist5.sort()
print(mylist5)
mylist5.reverse()
print(mylist5)
output
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
Dictionaries :
dict1 = {'key1':1, 'key2':2}
dict1.clear()
print(dict1)
output
{}
dict1 = {'key1':1, 'key2':2}
d1 = dict1.pop('key1')
print(d1)
print(dict1)
output
1
{'key2': 2}
dict2 = {'key1':1, 'key2':2}
mykey = [key for key in dict2]
print(mykey)
myvalue = [value for value in dict2.values()]
print(myvalue)
key_value = [(k, v) for k, v in dict2.items() ]
print(key_value)
output
['key1', 'key2']
[1, 2]
[('key1', 1), ('key2', 2)]
keys = ['zhangfei', 'guanyu', 'liubei', 'zhaoyun']
dict.fromkeys(keys, 0)
output
{'zhangfei': 0, 'guanyu': 0, 'liubei': 0, 'zhaoyun': 0}
Computers in the original design , Adopted 8 A bit (bit) As a byte (byte) The way . The largest integer a byte can represent is 255( Binary system 11111111= Decimal system 255), If you want to represent a larger integer , You have to use more bytes . Earliest , Computer only ASCII code , That is, it only contains upper and lower case English letters 、 Numbers and symbols , These are for other languages , Such as Chinese , Japanese is obviously not enough . Later, I invented Unicode,Unicode Unify all languages into one set of codes , So there won't be any more confusion . When you need to save to a hard disk or need to transfer , Just switch to UTF-8 code .UTF-8 It belongs to Unicode Variable length encoding method . stay Python in , With Unicode Method encoded string , have access to encode() Method to encode into the specified bytes, It can also be done through decode() The way to put bytes Encoded as a string .encode
" chinese ".encode('utf-8')
output
b'\xe4\xb8\xad\xe6\x96\x87'
decode
b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
output
' chinese '
1a = 1
2b = 2
3a, b = b, a
4print(a, b)
output
12 1
So let's do an example
c = d = [1,2]
e = [1,2]
print(c is d)
print(c == d)
print(c is e)
print(c == e)
output
True
True
False
True
== Comparison operator , Just judge the value of the object (value) Is it consistent , and is Then we judge the identity between objects ( Memory address ) Is it consistent . The identity of the object , Can pass id() Method to see
id(c)
id(d)
id(e)
output
88748080
88748080
88558288
It can be seen that , Only id Consistent time ,is Comparison will return True, And when value Consistent time ,== The comparison will return True
Positional arguments , Default parameters , Variable parameters , Key parameters
*arg
and **kwarg
effect Allows us to pass in multiple arguments when calling a function
def test(*arg, **kwarg):
if arg:
print("arg:", arg)
if kwarg:
print("kearg:", kwarg)
test('ni', 'hao', key='world')
output
arg: ('ni', 'hao')
kearg: {'key': 'world'}
It can be seen that ,*arg
It converts the position parameter to tuple**kwarg
Will convert keyword parameters to dict
sum(range(1, 101))
import time
import datetime
print(datetime.datetime.now())
print(time.strftime('%Y-%m-%d %H:%M:%S'))
output
2019-06-07 18:12:11.165330
2019-06-07 18:12:11
Simple list 10 strip : Try not to use small letters alone 'l', Capital 'O', And capital letters 'I' Wait for confusing letters . Function names are all lowercase , You can use underscores . Constant names are all uppercase , You can use underscores . Use has or is Prefix names Boolean elements , Such as : is_connect = True; has_member = False Don't put a semicolon at the end of the line , And don't use semicolons to put two commands on the same line . Don't use backslashes to connect lines . Empty space between top-level definitions 2 That's ok , Null between method definitions 1 That's ok , There are two empty lines between the top-level definitions . If a class does not inherit from other classes , It's obvious from object Inherit . Classes used internally 、 Method or variable , Prefix required _
Indicates that this is for internal use . To implement static type checking with assertions .
Shallow copy
import copy
list1 = [1, 2, 3, [1, 2]]
list2 = copy.copy(list1)
list2.append('a')
list2[3].append('a')
print(list1, list2)
output
[1, 2, 3, [1, 2, 'a']] [1, 2, 3, [1, 2, 'a'], 'a']
Can see , Shallow copies only succeed ” Independent “ Copied the outer layer of the list , And the inner list of the list , It's still shared
Deep copy
import copy
list1 = [1, 2, 3, [1, 2]]
list3 = copy.deepcopy(list1)
list3.append('a')
list3[3].append('a')
print(list1, list3)
output
[1, 2, 3, [1, 2]] [1, 2, 3, [1, 2, 'a'], 'a']
Deep copy makes the two lists completely independent , The operation of each list , Will not affect another
def num():
return [lambda x:i*x for i in range(4)]
print([m(1) for m in num()])
output
[3, 3, 3, 3]
By running the results , It can be seen that i The values for 3, Amazing
Variable data type :list、dict、set
Immutable data types :int/float、str、tuple
for i in range(1, 10):
for j in range(1, i+1):
print("%s*%s=%s " %(i, j, i*j), end="")
print()
output
1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
print function , The default is line feed , It has a default parameter end, If, for example , We put end The parameter display is set to "", that print After the function is executed , There will be no line change , In this way, the effect of 99 multiplication table is achieved
filter Function to filter the sequence , It receives a function and a sequence , Put the function on each element of the sequence , Then according to the return value is True still False Decide whether to keep or discard the element
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list(filter(lambda x: x%2 == 1, mylist))
output
[1, 3, 5, 7, 9]
Keep odd list
map Function passes in a function and a sequence , And apply the function to each element of the sequence , Returns an iteratable object
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list(map(lambda x: x*2, mylist))
output
[2, 4, 6, 8, 10, 12, 14, 16, 18]
reduce Function is used to recursively calculate , You also need to pass in a function and a sequence , The calculation results of function and sequence elements are calculated with the next element
from functools import reduce
reduce(lambda x, y: x+y, range(101))
output
5050
It can be seen that , The above three functions are used in combination with anonymous functions , Can write powerful and concise code
match() The function only detects whether the character to be matched is in string The start of the match ,search() Will scan the whole string Find a match
__new__
and __init__
difference __new__
It is called before the instance is created , Because its task is to create an instance and return the instance object , It's a static method .__init__
It is called when the instance object is created , Then set some initial values of the object properties , It is usually used to initialize a class instance , Is an example method
1、__new__
At least one parameter cls, Represents the current class , This parameter is instantiated by Python The interpreter automatically recognizes .2、__new__
There must be a return value , Return the instantiated instance , This is achieved by myself __new__
We should pay special attention to it , Sure return Parent class ( adopt super( The name of the class , cls))__new__
The examples come out , Or directly object Of __new__
The examples come out .3、__init__
There is a parameter self, This is this. __new__
The returned instance ,__init__
stay __new__
On the basis of this, we can complete some other initialization actions ,__init__
You don't need to return a value .4、 If __new__
Create an instance of the current class , Automatically called __init__
function , adopt return Statement __new__
The first argument to the function is cls To ensure that it is the current class instance , If it's the class name of another class ,; Then the actual creation returns instances of other classes , In fact, the current class will not be called __init__
function , No other classes will be called __init__
function
a, b = 1, 2
# provided that a>b establish It outputs a-b otherwise a+b
h = a-b if a>b else a+b
output
3
print(random.random())
print(random.randint(1, 100))
print(random.uniform(1,5))
output
0.03765019937131564
18
1.8458555362279228
zip() Function takes an iteratable object as an argument , Package the corresponding elements in the object into tuples , Then return a list of these tuples
list1 = ['zhangfei', 'guanyu', 'liubei', 'zhaoyun']
list2 = [0, 3, 2, 4]
list(zip(list1, list2))
output
[('zhangfei', 0), ('guanyu', 3), ('liubei', 2), ('zhaoyun', 4)]
range([start,] stop[, step]), according to start And stop Specified scope and step Set the step size , Generate a sequence . and xrange Generate a generator , It can save a lot of memory
Some exceptions may occur when opening a file for reading and writing , If you follow the routine f.open How to write it , We need to try,except,finally, Make abnormal judgment , And in the end, whatever happens to the file , To perform all finally f.close() Close file ,with Methods help us achieve finally in f.close
Python The default is greedy matching pattern
Greedy mode : Regular expressions tend to match the maximum length
Non greedy model : On the premise that the whole expression matches successfully , As few matches as possible
for example :
def test(L=[]):
L.append('test')
print(L)
output
test() # ['test']
test() # ['test', 'test']
The default parameter is a list , It's a mutable object [],Python At the time of function definition , Default parameters L The value of is calculated , yes [], Every time you call a function , If L The value of has changed , So the next time you call , The value of the default parameter is no longer [] 了
mystr = '1,2,3'
mystr.split(',')
output
['1', '2', '3']
mylist = ['1', '2', '3']
list(map(lambda x: int(x), mylist))
output
[1, 2, 3]
mylist = [1, 2, 3, 4, 5, 5]
list(set(mylist))
from collections import Counter
mystr = 'sdfsfsfsdfsd,were,hrhrgege.sdfwe!sfsdfs'
Counter(mystr)
output
Counter({'s': 9,
'd': 5,
'f': 7,
',': 2,
'w': 2,
'e': 5,
'r': 3,
'h': 2,
'g': 2,
'.': 1,
'!': 1})
[x for x in range(10) if x%2 == 1]
output
[1, 3, 5, 7, 9]
list1 = [[1,2],[3,4],[5,6]]
[j for i in list1 for j in i]
output
[1, 2, 3, 4, 5, 6]
Binary search algorithm is also called half search , The basic idea is to halve , Compare the size and then half find , It must be an ordered sequence to use binary search
A recursive algorithm
def binary_search(data, item):
# recursive
n = len(data)
if n > 0:
mid = n // 2
if data[mid] == item:
return True
elif data[mid] > item:
return binary_search(data[:mid], item)
else:
return binary_search(data[mid+1:], item)
return False
list1 = [1,4,5,66,78,99,100,101,233,250,444,890]
binary_search(list1, 999)
non-recursive algorithm
def binary_search(data, item):
# Non recursive
n = len(data)
first = 0
last = n - 1
while first <= last:
mid = (first + last)//2
if data[mid] == item:
return True
elif data[mid] > item:
last = mid - 1
else:
first = mid + 1
return False
list1 = [1,4,5,66,78,99,100,101,233,250,444,890]
binary_search(list1, 99)
Dictionary transfer json
import json
dict1 = {'zhangfei':1, "liubei":2, "guanyu": 4, "zhaoyun":3}
myjson = json.dumps(dict1)
myjson
output
'{"zhangfei": 1, "liubei": 2, "guanyu": 4, "zhaoyun": 3}'
json Turn Dictionary
mydict = json.loads(myjson)
mydict
output
{'zhangfei': 1, 'liubei': 2, 'guanyu': 4, 'zhaoyun': 3}
import random
td_list=[i for i in range(10)]
print(" List derivation ", td_list, type(td_list))
ge_list = (i for i in range(10))
print(" generator ", ge_list)
dic = {k:random.randint(4, 9)for k in ["a", "b", "c", "d"]}
print(" Dictionary derivation ",dic,type(dic))
output
List derivation [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>
generator <generator object <genexpr> at 0x0139F070>
Dictionary derivation {'a': 6, 'b': 5, 'c': 8, 'd': 9} <class 'dict'>
read Read entire file
readline Read next line , Using the generator method
readlines Read the entire file to an iterator for us to traverse
list2 = [1, 2, 3, 4, 5, 6]
random.shuffle(list2)
print(list2)
output
[4, 6, 5, 1, 2, 3]
str1 = 'luobodazahui'
str1[::-1]
output
'iuhazadoboul'
__foo__
: An agreement ,Python Internal name , Used to distinguish other user-defined names , In case of conflict , For example __init__()
,__del__()
,__call__()
Some special methods
_foo
: An agreement , Used to specify variable private . Out-of-service from module import * Import , Other aspects are accessed as public variables
__foo
: This has a real meaning : The parser uses _classname__foo
To replace the name , With the same name as other classes , It can't be accessed directly like a public member , By object name ._
Class name __xxx
This way you can access
a. stay python Rivan inherited object Class , It's all new
b. Python3 There are only new types in it
c. Python2 It's inherited object It's a new class , It's the classic class that doesn't write the parent class
d. Classic classes are currently in Python There's basically no application in it
a. Single inheritance and multiple inheritance are supported at the same time , Single inheritance when there is only one parent class , Multiple inheritance when there are multiple parent classes
b. The subclass inherits all the properties and methods of the parent class , Subclasses can also override variables and methods with the same name as the parent class
c. Construction of base class in inheritance (__init__()
) Method will not be called automatically , It needs to be specifically called in the construction of its derived class
d. When a method of a base class is called , Need to prefix the class name of the base class , And you need to bring it self Parameter variable . Unlike calling ordinary functions in classes, you don't need to bring them up. self Parameters
super() Function is used to call the parent class ( Superclass ) One way
class A():
def funcA(self):
print("this is func A")
class B(A):
def funcA_in_B(self):
super(B, self).funcA()
def funcC(self):
print("this is func C")
ins = B()
ins.funcA_in_B()
ins.funcC()
output
this is func A
this is func C
It is mainly divided into example method 、 Class methods and static methods
Example method
Definition : The first parameter must be an instance object , The parameter name is generally agreed as “self”, Pass the properties and methods of the instance through it ( You can also pass the properties and methods of a class )
call : Can only be called by instance object
Class method
Definition : Use decorators @classmethod. The first parameter must be the current class object , The parameter name is generally agreed as “cls”, Pass the properties and methods of the class through it ( Cannot pass instance properties and methods )
call : Instance objects and class objects can call
Static methods
Definition : Use decorators @staticmethod. Random parameters , No, “self” and “cls” Parameters , But you cannot use any properties or methods of a class or instance in a method body
call : Instance objects and class objects can call
Static methods are functions in a class , There is no need for instance . Static methods are mainly used to store logical code , Mainly some logic belongs to the class , But there is no interaction with the class itself . That is, in the static method , It doesn't involve the operation of methods and properties in the class . It can be understood that static methods exist in the namespace of this class
A class method is a method that operates on the class itself as an object . The difference between it and static methods is : Whether this method is called from an instance or from a class , It all passes the class with the first argument
Not bound to classes or instances function They all belong to functions (function)
Bound to classes and instances function They all belong to methods (method)
Ordinary function :
def func1():
pass
print(func1)
output
<function func1 at 0x01379348>
Functions in class :
class People(object):
def func2(self):
pass
@staticmethod
def func3():
pass
@classmethod
def func4(cls):
pass
people = People()
print(people.func2)
print(people.func3)
print(people.func4)
output
<bound method People.func2 of <__main__.People object at 0x013B8C90>>
<function People.func3 at 0x01379390>
<bound method People.func4 of <class '__main__.People'>>
isinstance() Function to determine whether an object is a known type , similar type()
difference :
type() A subclass is not considered a superclass type , Do not consider inheritance relationships
isinstance() Think of a subclass as a superclass type , Consider inheritance relationships
class A(object):
pass
class B(A):
pass
a = A()
b = B()
print(isinstance(a, A))
print(isinstance(b, A))
print(type(a) == A)
print(type(b) == A)
output
True
True
True
False
The singleton pattern : The main purpose is to ensure that only one instance of a class exists
Factory mode : Include a superclass , This superclass provides an abstract interface to create a specific type of object , Instead of deciding which object can be created
import os
print(os.listdir('.'))
# 1 To 5 Consisting of three digits that do not repeat each other
k = 0
for i in range(1, 6):
for j in range(1, 6):
for z in range(1, 6):
if (i != j) and (i != z) and (j != z):
k += 1
if k%6:
print("%s%s%s" %(i, j, z), end="|")
else:
print("%s%s%s" %(i, j, z))
output
123|124|125|132|134|135
142|143|145|152|153|154
213|214|215|231|234|235
241|243|245|251|253|254
312|314|315|321|324|325
341|342|345|351|352|354
412|413|415|421|423|425
431|432|435|451|452|453
512|513|514|521|523|524
531|532|534|541|542|543
str1 = " hello nihao "
str1.strip()
output
'hello nihao'
str2 = "hello you are good"
print(str2.replace(" ", ""))
"".join(str2.split(" "))
output
helloyouaregood
'helloyouaregood'
print("This is for %s" % "Python")
print("This is for %s, and %s" %("Python", "You"))
output
This is for Python
This is for Python, and You
stay Python3 in , This new string formatting method is introduced
print("This is my {}".format("chat"))
print("This is {name}, hope you can {do}".format(name="zhouluob", do="like"))
output
This is my chat
This is zhouluob, hope you can like
stay Python3-6 in , This new string formatting method is introduced
name = "luobodazahui"
print(f"hello {name}")
output
hello luobodazahui
A more complicated example :
def mytest(name, age):
return f"hello {name}, you are {age} years old!"
people = mytest("luobo", 20)
print(people)
output
hello luobo, you are 20 years old!
str1 = "hello world"
print(str1.title())
" ".join(list(map(lambda x: x.capitalize(), str1.split(" "))))
output
Hello World
'Hello World'
Such as :[1, 2, 3] -> ["1", "2", "3"]
list1 = [1, 2, 3]
list(map(lambda x: str(x), list1))
output
['1', '2', '3']
Such as :("zhangfei", "guanyu"),(66, 80) -> {'zhangfei': 66, 'guanyu': 80}
a = ("zhangfei", "guanyu")
b = (66, 80)
dict(zip(a,b))
output
{'zhangfei': 66, 'guanyu': 80}
Example 1:
a = (1,2,3,[4,5,6,7],8)
a[3] = 2
output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-35-59469d550eb0> in <module>
1 a = (1,2,3,[4,5,6,7],8)
----> 2 a[3] = 2
3 #a
TypeError: 'tuple' object does not support item assignment
Example 2:
a = (1,2,3,[4,5,6,7],8)
a[3][2] = 2
a
output
(1, 2, 3, [4, 5, 2, 7], 8)
From the example 1 It can be seen from the error report of ,tuple It's an immutable type , Can't change tuple Elements in , Example 2 in ,list It's a variable type , Changing its elements is allowed
Reflection is in the form of strings , The import module ; In the form of strings , Go to the module to find the specified function , And implement . Use the form of string to remove objects ( modular ) In the operation ( lookup / obtain / Delete / add to ) member , A string based event driver !
Simple understanding is used to determine what a string is , Variables or methods
class NewClass(object):
def __init__(self, name, male):
self.name = name
self.male = male
def myname(self):
print(f'My name is {self.name}')
def mymale(self):
print(f'I am a {self.male}')
people = NewClass('luobo', 'boy')
print(hasattr(people, 'name'))
print(getattr(people, 'name'))
setattr(people, 'male', 'girl')
print(getattr(people, 'male'))
output
True
luobo
girl
getattr,hasattr,setattr,delattr Changes to the module are made in memory , It doesn't affect the real content of the file
Use flask structure web The server
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['POST'])
def simple_api():
result = request.get_json()
return result
if __name__ == "__main__":
app.run()
Class and instance :
First define the class, then , You can create instances based on this class , therefore : First define classes , Then create an instance
Class and metaclass :
First define metaclasses , according to metaclass Create a class , therefore : First define metaclass, Then create the class
class MyMetaclass(type):
def __new__(cls, class_name, class_parents, class_attr):
class_attr['print'] = "this is my metaclass's subclass %s" %class_name
return type.__new__(cls, class_name, class_parents, class_attr)
class MyNewclass(object, metaclass=MyMetaclass):
pass
myinstance = MyNewclass()
myinstance.print
output
"this is my metaclass's subclass MyNewclass"56. Python Reflection in
Reflection is in the form of strings , The import module ; In the form of strings , Go to the module to find the specified function , And implement . Use the form of string to remove objects ( modular ) In the operation ( lookup / obtain / Delete / add to ) member , A string based event driver !
Simple understanding is used to determine what a string is , Variables or methods
class NewClass(object):
def __init__(self, name, male):
self.name = name
self.male = male
def myname(self):
print(f'My name is {self.name}')
def mymale(self):
print(f'I am a {self.male}')
people = NewClass('luobo', 'boy')
print(hasattr(people, 'name'))
print(getattr(people, 'name'))
setattr(people, 'male', 'girl')
print(getattr(people, 'male'))
output
True
luobo
girl
getattr,hasattr,setattr,delattr Changes to the module are made in memory , It doesn't affect the real content of the file
57. Implement a simple one API
Use flask structure web The server
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['POST'])
def simple_api():
result = request.get_json()
return result
if __name__ == "__main__":
app.run()
58. metaclass The metaclass
Class and instance :
First define the class, then , You can create instances based on this class , therefore : First define classes , Then create an instance
Class and metaclass :
First define metaclasses , according to metaclass Create a class , therefore : First define metaclass, Then create the class
class MyMetaclass(type):
def __new__(cls, class_name, class_parents, class_attr):
class_attr['print'] = "this is my metaclass's subclass %s" %class_name
return type.__new__(cls, class_name, class_parents, class_attr)
class MyNewclass(object, metaclass=MyMetaclass):
pass
myinstance = MyNewclass()
myinstance.print
output
"this is my metaclass's subclass MyNewclass"
sort() It's a list of variable objects (list) Methods , No parameter , No return value ,sort() Will change the mutable objects
dict1 = {'test1':1, 'test2':2}
list1 = [2, 1, 3]
print(list1.sort())
list1
output
None
[1, 2, 3]
sorted() It's about creating a new object .sorted(L) Returns a sorted L, Don't change the original L,sorted() Applicable to any iteratable container
dict1 = {'test1':1, 'test2':2}
list1 = [2, 1, 3]
print(sorted(dict1))print(sorted(list1))
output
['test1', 'test2']
[1, 2, 3]
GIL yes Python The global interpreter lock , If there are multiple threads running in the same process , A thread is running Python The program will take up Python Interpreter ( Add a lock, that is GIL), Make other threads in the process unable to run , After the thread has finished running, other threads can run . If a thread runs into time-consuming operations , The interpreter lock is released , Make other threads run . So in multithreading , Threads still run in sequence , Not at the same time
import random
"".join(random.choice(string.printable[:-7]) for i in range(8))
output
'd5^NdNJp'
print('hello\nworld')
print(b'hello\nworld')
print(r'hello\nworld')
output
hello
world
b'hello\nworld'
hello\nworld
list1 = [{'name': 'guanyu', 'age':29},
{'name': 'zhangfei', 'age': 28},
{'name': 'liubei', 'age':31}]
sorted(list1, key=lambda x:x['age'])
output
[{'name': 'zhangfei', 'age': 28},
{'name': 'guanyu', 'age': 29},
{'name': 'liubei', 'age': 31}]
all If there is 0 Null False return False, Otherwise return to True;any If it's all 0,None,False,Null when , return True
print(all([1, 2, 3, 0]))
print(all([1, 2, 3]))
print(any([1, 2, 3, 0]))
print(any([0, None, False]))
output
False
True
True
False
def reverse_int(x):
if not isinstance(x, int):
return False
if -10 < x < 10:
return x
tmp = str(x)
if tmp[0] != '-':
tmp = tmp[::-1]
return int(tmp)
else:
tmp = tmp[1:][::-1]
x = int(tmp)
return -x
reverse_int(-23837)
output
-73832
First, judge whether it is an integer , Then judge whether it is a number , Finally, judge whether it is a negative number
Functional programming is a highly abstract programming paradigm , Functions written in pure functional programming languages have no variables , therefore , Any function , As long as the input is certain , The output is certain , This pure function is called no side effects . And programming languages that allow variables , Because the state of the variable inside the function is uncertain , Same input , It's possible to get different output , therefore , This function has side effects . because Python Allow variables , therefore ,Python It's not a pure functional programming language
One of the features of functional programming is , Allows the function itself to be passed as an argument to another function , It also allows you to return a function !
Function as an example of the return value :
def sum(*args):
def inner_sum():
tmp = 0
for i in args:
tmp += i
return tmp
return inner_sum
mysum = sum(2, 4, 6)
print(type(mysum))
mysum()
output
<class 'function'>
12
If it's in an internal function , On the external scope ( But not in the global scope ) The variables are quoted , So internal functions are considered closures (closure) Attach the function scope picture
Closure characteristics
1. Must have an embedded function
2. An embedded function must refer to a variable in an external function
3. The return value of an external function must be an embedded function
Decorators are special closures , That is to pass a function on the basis of closure , Then override the execution entry of the original function , When you call this function later, , You can do some extra functions
A print log Example :
import time
def log(func):
def inner_log(*args, **kw):
print("Call: {}".format(func.__name__))
return func(*args, **kw)
return inner_log
@log
def timer():
print(time.time())
timer()
output
Call: timer
1560171403.5128365
Essentially ,decorator It's a higher-order function that returns a function
Subroutine switching is not thread switching , It's controlled by the program itself
There is no overhead for thread switching , Ratio to multithreading , The more threads there are , The greater the performance advantage of the coroutine
No multi-threaded locking mechanism is required , Because there's only one thread , There is no conflict between writing variables at the same time , Control Shared resources without locking in the coroutine
Fibonacci sequence :
Also called golden section series , It refers to such a sequence :1、1、2、3、5、8、13、21、34、…… In Mathematics , Fibonacci sequence is defined recursively as follows :F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)(n>=2,n∈N*)
Generator method :
def fib(n):
if n == 0:
return False
if not isinstance(n, int) or (abs(n) != n): # It's a positive integer
return False
a, b = 0, 1
while n:
a, b = b, a+b
n -= 1
yield a
[i for i in fib(10)]
output
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Recursive method :
def fib(n):
if n == 0:
return False
if not isinstance(n, int) or (abs(n) != n):
return False
if n <= 1:
return n
return fib(n-1)+ fib(n-2)
[fib(i) for i in range(1, 11)]
output
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
import re
str1 = 'hello world:luobo dazahui'
result = re.split(r":| ", str1)
print(result)
output
['hello', 'world', 'luobo', 'dazahui']
yield Is the syntax used to generate iterators , In the function , If included yield, So this function is an iterator . When the code is executed to yield when , Will interrupt code execution , Until the program calls next() Function time , Only last time yield Where to continue to carry out
def foryield():
print("start test yield")
while True:
result = yield 5
print("result:", result)
g = foryield()
print(next(g))
print("*"*20)
print(next(g))
output
start test yield
5
********************
result: None
5
You can see , The first call next() function , The program just goes to "result = yield 5" here , At the same time as yield Interrupted the program , therefore result It's not assigned either , So the second execution next() when ,result yes None
list1 = [2, 5, 8, 9, 3, 11]
def paixu(data, reverse=False):
if not reverse:
for i in range(len(data) - 1):
for j in range(len(data) - 1 - i):
if data[j] > data[j+1]:
data[j], data[j+1] = data[j+1], data[j]
return data
else:
for i in range(len(data) - 1):
for j in range(len(data) - 1 - i):
if data[j] < data[j+1]:
data[j], data[j+1] = data[j+1], data[j]
return data
print(paixu(list1, reverse=True))
output
[11, 9, 8, 5, 3, 2]
Fast thinking : So let's just pick an arbitrary number ( The first number of the array is usually chosen ) As key data , And then I'm going to put all the smaller Numbers in front of it , All the Numbers that are bigger than that are going to go after that , This process is called a quick sort , And then recursively sort the data on both sides
Select benchmark : Pick a member of the sequence , be called " The benchmark "(pivot)
Division : Reorder the sequence , All elements smaller than the benchmark value are placed in front of the benchmark , All elements larger than the reference value are placed behind the reference ( A number equal to the reference value can go to either side )
After this split , Sorting the baseline values is complete
Recursively sort subsequences : Recursively sorts subsequences that are less than the base value element and subsequences that are greater than the base value element
list1 = [8, 5, 1, 3, 2, 10, 11, 4, 12, 20]
def partition(arr,low,high):
i = ( low-1 ) # Minimum element index
pivot = arr[high]
for j in range(low , high):
# The current element is less than or equal to pivot
if arr[j] <= pivot:
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return ( i+1 )
def quicksort(arr,low,high):
if low < high:
pi = partition(arr,low,high)
quicksort(arr, low, pi-1)
quicksort(arr, pi+1, high)
quicksort(list1, 0, len(list1)-1)
print(list1)
output
[1, 2, 3, 4, 5, 8, 10, 11, 12, 20]
The library is initiated by HTTP Powerful library of requests , Easy to call , Powerful
import requests
url = "http://www.luobodazahui.top"
response = requests.get(url) # Get the request
response.encoding = "utf-8" # Change the code
html = response.text # Get web content
binary__content = response.content # Get binary data
raw = requests.get(url, stream=True) # Get the original response content
headers = {'user-agent': 'my-test/0.1.1'} # Custom request header
r = requests.get(url, headers=headers)
cookies = {"cookie": "# your cookie"} # cookie Use
r = requests.get(url, cookies=cookies)
dict1 = {"zhangfei": 12, "guanyu": 13, "liubei": 18}
dict2 = {"zhangfei": 12, "guanyu": 13, "liubei": 18}
def compare_dict(dict1, dict2):
issame = []
for k in dict1.keys():
if k in dict2:
if dict1[k] == dict2[k]:
issame.append(1)
else:
issame.append(2)
else:
issame.append(3)
print(issame)
sum_except = len(issame)
sum_actually = sum(issame)
if sum_except == sum_actually:
print("this two dict are same!")
return True
else:
print("this two dict are not same!")
return False
test = compare_dict(dict1, dict2)
output
[1, 1, 1]
this two dict are same!
input() function
def forinput():
input_text = input()
print("your input text is: ", input_text)
forinput()
output
hello
your input text is: hello
enumerate() Function is used to traverse a data object ( As listing 、 Tuples or strings ) Combined into an index sequence , List both data and data index , Generally used in for Cycle of
data1 = ['one', 'two', 'three', 'four']
for i, enu in enumerate(data1):
print(i, enu)
output
0 one
1 two
2 three
3 four
pass It's an empty statement , To maintain the integrity of the program structure .pass Not doing anything , Generally used as occupation statement
def forpass(n):
if n == 1:
pass
else:
print('not 1')
forpass(1)
import re
email_list= ["[email protected]","[email protected]", "[email protected]", "[email protected]" ]
for email in email_list:
ret = re.match("[\w]{4,20}@(.*)\.com$",email)
if ret:
print("%s It's a compliant email address , After matching, the result is :%s" % (email,ret.group()))
else:
print("%s Unqualified " % email)
output
[email protected] It's a compliant email address , After matching, the result is :[email protected]
[email protected] Unqualified
[email protected] Unqualified
[email protected] It's a compliant email address , After matching, the result is :[email protected]
str2 = 'werrQWSDdiWuW'
counter = 0
for i in str2:
if i.isupper():
counter += 1
print(counter)
output
6
Normal serialization :
import json
dict1 = {'name': ' radish ', 'age': 18}
dict1_new = json.dumps(dict1)
print(dict1_new)
output
{"name": "\u841d\u535c", "age": 18}
Keep Chinese
import json
dict1 = {'name': ' radish ', 'age': 18}
dict1_new = json.dumps(dict1, ensure_ascii=False)
print(dict1_new)
output
{"name": " radish ", "age": 18}
One class inherits from another , It can also be said to be a child class / Derived class / Subclass , Inherited from the parent class / Base class / Superclass , Get all class members at the same time ( Properties and methods )
Inheritance allows us to reuse code , And it's easier to create and maintain code
Python Supports the following types of inheritance :
Single inheritance - A subclass inherits from a single base class
multiple inheritance - A subclass inherits from more than one base class
Multilevel inheritance - A subclass inherits from a base class , The base class inherits from another base class
Hierarchical inheritance - Multiple subclasses inherit from the same base class
Mixed inheritance - A combination of two or more inheritance types
Monkey patch refers to dynamically modifying classes and modules at runtime
Monkey patch mainly has the following uses :
Replace methods at run time 、 Properties, etc
Add functions that were not supported before without modifying the third-party code
Add... To objects in memory at run time patch Instead of adding... To the disk's source code
help() Function returns help documentation and parameter descriptions :
help(dict)
output
Help on class dict in module builtins:
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
......
dir() Function returns all members of the object ( Any kind of )
dir(dict)
output
['__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
......
//
,%
and **
Operator //
Operator performs floor Division , Returns the integer part of the result ( Rounding down )
%
It's a modulo symbol , Returns the remainder of the division
**
The sign denotes exponentiation . a**b return a Of b Power
print(5//3)
print(5/3)
print(5%3)
print(5**3)
output
1
1.6666666666666667
2
125
The library is initiated by HTTP Powerful library of requests , Easy to call , Powerful
import requests
url = "http://www.luobodazahui.top"
response = requests.get(url) # Get the request
response.encoding = "utf-8" # Change the code
html = response.text # Get web content
binary__content = response.content # Get binary data
raw = requests.get(url, stream=True) # Get the original response content
headers = {'user-agent': 'my-test/0.1.1'} # Custom request header
r = requests.get(url, headers=headers)
cookies = {"cookie": "# your cookie"} # cookie Use
r = requests.get(url, cookies=cookies)
dict1 = {"zhangfei": 12, "guanyu": 13, "liubei": 18}
dict2 = {"zhangfei": 12, "guanyu": 13, "liubei": 18}
def compare_dict(dict1, dict2):
issame = []
for k in dict1.keys():
if k in dict2:
if dict1[k] == dict2[k]:
issame.append(1)
else:
issame.append(2)
else:
issame.append(3)
print(issame)
sum_except = len(issame)
sum_actually = sum(issame)
if sum_except == sum_actually:
print("this two dict are same!")
return True
else:
print("this two dict are not same!")
return False
test = compare_dict(dict1, dict2)
output
[1, 1, 1]
this two dict are same!
input() function
def forinput():
input_text = input()
print("your input text is: ", input_text)
forinput()
output
hello
your input text is: hello
enumerate() Function is used to traverse a data object ( As listing 、 Tuples or strings ) Combined into an index sequence , List both data and data index , Generally used in for Cycle of
data1 = ['one', 'two', 'three', 'four']
for i, enu in enumerate(data1):
print(i, enu)
output
0 one
1 two
2 three
3 four
pass It's an empty statement , To maintain the integrity of the program structure .pass Not doing anything , Generally used as occupation statement
def forpass(n):
if n == 1:
pass
else:
print('not 1')
forpass(1)
import re
email_list= ["[email protected]","[email protected]", "[email protected]", "[email protected]" ]
for email in email_list:
ret = re.match("[\w]{4,20}@(.*)\.com$",email)
if ret:
print("%s It's a compliant email address , After matching, the result is :%s" % (email,ret.group()))
else:
print("%s Unqualified " % email)
output
[email protected] It's a compliant email address , After matching, the result is :[email protected]
[email protected] Unqualified
[email protected] Unqualified
[email protected] It's a compliant email address , After matching, the result is :[email protected]
str2 = 'werrQWSDdiWuW'
counter = 0
for i in str2:
if i.isupper():
counter += 1
print(counter)
output
6
Normal serialization :
import json
dict1 = {'name': ' radish ', 'age': 18}
dict1_new = json.dumps(dict1)
print(dict1_new)
output
{"name": "\u841d\u535c", "age": 18}
Keep Chinese
import json
dict1 = {'name': ' radish ', 'age': 18}
dict1_new = json.dumps(dict1, ensure_ascii=False)
print(dict1_new)
output
{"name": " radish ", "age": 18}
One class inherits from another , It can also be said to be a child class / Derived class / Subclass , Inherited from the parent class / Base class / Superclass , Get all class members at the same time ( Properties and methods )
Inheritance allows us to reuse code , And it's easier to create and maintain code
Python Supports the following types of inheritance :
Single inheritance - A subclass inherits from a single base class
multiple inheritance - A subclass inherits from more than one base class
Multilevel inheritance - A subclass inherits from a base class , The base class inherits from another base class
Hierarchical inheritance - Multiple subclasses inherit from the same base class
Mixed inheritance - A combination of two or more inheritance types
Monkey patch refers to dynamically modifying classes and modules at runtime
Monkey patch mainly has the following uses :
Replace methods at run time 、 Properties, etc
Add functions that were not supported before without modifying the third-party code
Add... To objects in memory at run time patch Instead of adding... To the disk's source code
help() Function returns help documentation and parameter descriptions :
help(dict)
output
Help on class dict in module builtins:
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
......
dir() Function returns all members of the object ( Any kind of )
dir(dict)
output
['__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
......
//
,%
and **
Operator //
Operator performs floor Division , Returns the integer part of the result ( Rounding down )
%
It's a modulo symbol , Returns the remainder of the division
**
The sign denotes exponentiation . a**b return a Of b Power
print(5//3)
print(5/3)
print(5%3)
print(5**3)
output
1
1.6666666666666667
2
125
Use raise
def test_raise(n):
if not isinstance(n, int):
raise Exception('not a int type')
else:
print('good')
test_raise(8.9)
output
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-262-b45324f5484e> in <module>
4 else:
5 print('good')
----> 6 test_raise(8.9)
<ipython-input-262-b45324f5484e> in test_raise(n)
1 def test_raise(n):
2 if not isinstance(n, int):
----> 3 raise Exception('not a int type')
4 else:
5 print('good')
Exception: not a int type
tuple1 = (1, 2, 3, 4)
list1 = list(tuple1)
print(list1)
tuple2 = tuple(list1)
print(tuple2)
output
[1, 2, 3, 4](1, 2, 3, 4)
Python The assertion of is to detect a condition , If the condition is true , It does nothing ; Instead, it triggers a... With an optional error message AssertionError
def testassert(n):
assert n == 2, "n is not 2"
print('n is 2')
testassert(1)
output
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-268-a9dfd6c79e73> in <module>
2 assert n == 2, "n is not 2"
3 print('n is 2')
----> 4 testassert(1)
<ipython-input-268-a9dfd6c79e73> in testassert(n)
1 def testassert(n):
----> 2 assert n == 2, "n is not 2"
3 print('n is 2')
4 testassert(1)
AssertionError: n is not 2
Asynchrony refers to the relationship between the caller and the callee
So called synchronization , When a function call is issued , Before we get results , The call will not return , Once called back , You get the return value
The concept of asynchrony is relative to synchronization , The call is made after , This call returns directly , So no results returned . When the asynchronous function is completed , The callee can use the State 、 Notify or callback to notify the caller
Blocking non blocking is the relationship between threads or processes
Blocking call refers to the call result before returning , The current thread will be suspended ( If encountered io operation ). The calling thread will return... Only after it gets the result . The function will only activate the blocked thread if it gets the result
The concepts of non blocking and blocking correspond , A nonblocking call means that it returns immediately before it can get the result immediately , At the same time, this function will not block the current thread
Python The sequence in is indexed , It's made up of positive and negative numbers . Positive numbers use '0' As the first index ,'1' As the second index , And so on
The index of a negative number is from '-1' Start , Represents the last index in the sequence ,' - 2' As the penultimate index , By analogy
No, it isn't , Variables with object circular references or global namespace references , stay Python It's not always released when you exit
In addition, it will not release C Part of what the library keeps
Flask yes “microframework”, Mainly used to write small applications , But as the Python The popularity of , A lot of big programs are also in use Flask. meanwhile , stay Flask in , We have to use external libraries
Django For large applications . It provides flexibility , And complete program framework and fast project generation method . You can choose different databases ,URL structure , Template style, etc
import os
f = open('test.txt', 'w')
f.close()
os.listdir()
os.remove('test.txt')
logging The module is Python Built in standard modules , It is mainly used to output the operation log , You can set the level of output log 、 Log save path 、 Log file rollback, etc ; comparison print, It has the following advantages :
You can set different log levels , stay release Only important information is output in the version , Without having to display a lot of debugging information
print Output all information to standard output , Seriously affect developers to view other data from standard output ;logging It's up to the developer to decide where to output the information , And how to output
Simple configuration :
import logging
logging.debug("debug log")
logging.info("info log")
logging.warning("warning log")
logging.error("error log")
logging.critical("critica log")
output
WARNING:root:warning log
ERROR:root:error log
CRITICAL:root:critica log
By default , Only greater than or equal to is displayed WARNING Level of logging .logging.basicConfig() Function to adjust the log level 、 Output format, etc
from collections import Counter
str1 = "nihsasehndciswemeotpxc"
print(Counter(str1))
output
Counter({'s': 3, 'e': 3, 'n': 2, 'i': 2, 'h': 2, 'c': 2, 'a': 1, 'd': 1, 'w': 1, 'm': 1, 'o': 1, 't': 1, 'p': 1, 'x': 1})
re.compile Is to compile a regular expression into an object , Speed up , And reuse
try..except..else No exception was caught , perform else sentence
try..except..finally Whether or not an exception is caught , All implemented finally sentence
Using slice :
$ python -m timeit -n 1000000 -s 'import numpy as np' 'mylist=list(np.arange(0, 200))' 'mylist[::-1]'
1000000 loops, best of 5: 15.6 usec per loop
Use reverse():
$ python -m timeit -n 1000000 -s 'import numpy as np' 'mylist=list(np.arange(0, 200))' 'mylist.reverse()'
1000000 loops, best of 5: 10.7 usec per loop
Both methods can reverse the list , But it should be noted that the built-in functions reverse() Will change the original list , The slicing method creates a new list .
obviously , Built in functions reverse() Faster than list slicing !
Use re Regular substitution
import re
str1 = ' I'm Zhou radish , This year, 18 year '
result = re.sub(r"\d+","20",str1)
print(result)
output
I'm Zhou radish , This year, 20 year
Elder martial brother Ali sorted it out 170 Avenue Python Complete interview questions PDF Download address
Catalog Python Script editing
Python Exception handling mech