你见过的最全面的 Python 重点

2019-11-27  本文已影响0人  视学算法

作者:二十一

链接:https://segmentfault.com/a/1190000018737045

由于总结了太多的东西,所以篇幅有点长,这也是我"缝缝补补"总结了好久的东西。

Py2 VS Py3

#枚举的注意事项
from enum import Enum

class COLOR(Enum):
YELLOW=1
#YELLOW=2#会报错
GREEN=1#不会报错,GREEN可以看作是YELLOW的别名
BLACK=3
RED=4
print(COLOR.GREEN)#COLOR.YELLOW,还是会打印出YELLOW
for i in COLOR:#遍历一下COLOR并不会有GREEN
print(i)
#COLOR.YELLOW
COLOR.BLACK
COLOR.RED
怎么把别名遍历出来

for i in COLOR.__members__.items():
print(i)
# output:('YELLOW', <COLOR.YELLOW: 1>)
('GREEN', <COLOR.YELLOW: 1>)
('BLACK', <COLOR.BLACK: 3>)
('RED', <COLOR.RED: 4>)

for i in COLOR.__members__:
print(i)
# output:YELLOW
GREEN
BLACK
RED


#枚举转换
#最好在数据库存取使用枚举的数值而不是使用标签名字字符串
#在代码里面使用枚举类
a=1
print(COLOR(a))# output:COLOR.YELLOW

py2/3转换工具

常用的库

不常用但很重要的库

    def isLen(strString):
#还是应该使用三元表达式,更快
return True if len(strString)>6 else False

def isLen1(strString):
#这里注意false和true的位置
return [False,True][len(strString)>6]
import timeit
print(timeit.timeit('isLen1("5fsdfsdfsaf")',setup="from __main__ import isLen1"))

print(timeit.timeit('isLen("5fsdfsdfsaf")',setup="from __main__ import isLen"))
    import types
types.coroutine #相当于实现了__await__
    import html
html.escape("<h1>I'm Jim</h1>") # output:'&lt;h1&gt;I&#x27;m Jim&lt;/h1&gt;'
html.unescape('&lt;h1&gt;I&#x27;m Jim&lt;/h1&gt;') # <h1>I'm Jim</h1>
from concurrent.futures import ThreadPoolExecutor

pool = ThreadPoolExecutor()
task = pool.submit(函数名,(参数)) #此方法不会阻塞,会立即返回
task.done()#查看任务执行是否完成
task.result()#阻塞的方法,查看任务返回值
task.cancel()#取消未执行的任务,返回True或False,取消成功返回True
task.add_done_callback()#回调函数
task.running()#是否正在执行 task就是一个Future对象

for data in pool.map(函数,参数列表):#返回已经完成的任务结果列表,根据参数顺序执行
print(返回任务完成得执行结果data)

from concurrent.futures import as_completed
as_completed(任务列表)#返回已经完成的任务列表,完成一个执行一个

wait(任务列表,return_when=条件)#根据条件进行阻塞主线程,有四个条件
future=asyncio.ensure_future(协程)  等于后面的方式  future=loop.create_task(协程)
future.add_done_callback()添加一个完成后的回调函数
loop.run_until_complete(future)
future.result()查看写成返回结果

asyncio.wait()接受一个可迭代的协程对象
asynicio.gather(*可迭代对象,*可迭代对象) 两者结果相同,但gather可以批量取消,gather对象.cancel()

一个线程中只有一个loop

在loop.stop时一定要loop.run_forever()否则会报错
loop.run_forever()可以执行非协程
最后执行finally模块中 loop.close()

asyncio.Task.all_tasks()拿到所有任务 然后依次迭代并使用任务.cancel()取消

偏函数partial(函数,参数)把函数包装成另一个函数名 其参数必须放在定义函数的前面

loop.call_soon(函数,参数)
call_soon_threadsafe()线程安全
loop.call_later(时间,函数,参数)
在同一代码块中call_soon优先执行,然后多个later根据时间的升序进行执行

如果非要运行有阻塞的代码
使用loop.run_in_executor(executor,函数,参数)包装成一个多线程,然后放入到一个task列表中,通过wait(task列表)来运行

通过asyncio实现http
reader,writer=await asyncio.open_connection(host,port)
writer.writer()发送请求
async for data in reader:
data=data.decode("utf-8")
list.append(data)
然后list中存储的就是html

as_completed(tasks)完成一个返回一个,返回的是一个可迭代对象

协程锁
async with Lock():

Python进阶

from multiprocessing import Manager,Process
def add_data(p_dict, key, value):
p_dict[key] = value

if __name__ == "__main__":
progress_dict = Manager().dict()
from queue import PriorityQueue

first_progress = Process(target=add_data, args=(progress_dict, "bobby1", 22))
second_progress = Process(target=add_data, args=(progress_dict, "bobby2", 23))

first_progress.start()
second_progress.start()
first_progress.join()
second_progress.join()

print(progress_dict)
from multiprocessing import Pipe,Process
#pipe的性能高于queue
def producer(pipe):
pipe.send("bobby")

def consumer(pipe):
print(pipe.recv())

if __name__ == "__main__":
recevie_pipe, send_pipe = Pipe()
#pipe只能适用于两个进程
my_producer= Process(target=producer, args=(send_pipe, ))
my_consumer = Process(target=consumer, args=(recevie_pipe,))

my_producer.start()
my_consumer.start()
my_producer.join()
my_consumer.join()
from multiprocessing import Queue,Process
def producer(queue):
queue.put("a")
time.sleep(2)

def consumer(queue):
time.sleep(2)
data = queue.get()
print(data)

if __name__ == "__main__":
queue = Queue(10)
my_producer = Process(target=producer, args=(queue,))
my_consumer = Process(target=consumer, args=(queue,))
my_producer.start()
my_consumer.start()
my_producer.join()
my_consumer.join()
def producer(queue):
queue.put("a")
time.sleep(2)

def consumer(queue):
time.sleep(2)
data = queue.get()
print(data)

if __name__ == "__main__":
queue = Manager().Queue(10)
pool = Pool(2)

pool.apply_async(producer, args=(queue,))
pool.apply_async(consumer, args=(queue,))

pool.close()
pool.join()
    # 方法一
True in [i in s for i in [a,b,c]]
# 方法二
any(i in s for i in [a,b,c])
# 方法三
list(filter(lambda x:x in s,[a,b,c]))
    import sys
sys.getdefaultencoding() # setdefaultencodeing()设置系统编码方式
class A(dict):
def __getattr__(self,value):#当访问属性不存在的时候返回
return 2
def __getattribute__(self,item):#屏蔽所有的元素访问
return item
    print([[x for x in range(1,101)][i:i+3] for i in range(0,100,3)])
type.__bases__  #(<class 'object'>,)
object.__bases__ #()
type(object) #<class 'type'>
    class Yuan(type):
def __new__(cls,name,base,attr,*args,**kwargs):
return type(name,base,attr,*args,**kwargs)
class MyClass(metaclass=Yuan):
pass
    class MyTest(unittest.TestCase):
def tearDown(self):# 每个测试用例执行前执行
print('本方法开始测试了')

def setUp(self):# 每个测试用例执行之前做操作
print('本方法测试结束')

@classmethod
def tearDownClass(self):# 必须使用 @ classmethod装饰器, 所有test运行完后运行一次
print('开始测试')
@classmethod
def setUpClass(self):# 必须使用@classmethod 装饰器,所有test运行前运行一次
print('结束测试')

def test_a_run(self):
self.assertEqual(1, 1) # 测试用例
    for gevent import monkey
monkey.patch_all() #将代码中所有的阻塞方法都进行修改,可以指定具体要修改的方法
    co_flags = func.__code__.co_flags

# 检查是否是协程
if co_flags & 0x180:
return func

# 检查是否是生成器
if co_flags & 0x20:
return func
#一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
#请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
#方式一:
fib = lambda n: n if n <= 2 else fib(n - 1) + fib(n - 2)
#方式二:
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return b

#一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
fib = lambda n: n if n < 2 else 2 * fib(n - 1)
    import os
os.getenv(env_name,None)#获取环境变量如果不存在为None
    #查看分代回收触发
import gc
gc.get_threshold() #output:(700, 10, 10)
    def conver_bin(num):
if num == 0:
return num
re = []
while num:
num, rem = divmod(num,2)
re.append(str(rem))
return "".join(reversed(re))
conver_bin(10)
    list1 = ['A', 'B', 'C', 'D']

# 方法一
for i in list1:
globals()[i] = [] # 可以用于实现python版反射

# 方法二
for i in list1:
exec(f'{i} = []') # exec执行字符串语句
    # bytearray是可变的,bytes是不可变的,memoryview不会产生新切片和对象
a = 'aaaaaa'
ma = memoryview(a)
ma.readonly # 只读的memoryview
mb = ma[:2] # 不会产生新的字符串

a = bytearray('aaaaaa')
ma = memoryview(a)
ma.readonly # 可写的memoryview
mb = ma[:2] # 不会会产生新的bytearray
mb[:2] = 'bb' # 对mb的改动就是对ma的改动
# 代码中出现...省略号的现象就是一个Ellipsis对象
L = [1,2,3]
L.append(L)
print(L) # output:[1,2,3,[…]]
    class lazy(object):
def __init__(self, func):
self.func = func

def __get__(self, instance, cls):
val = self.func(instance) #其相当于执行的area(c),c为下面的Circle对象
setattr(instance, self.func.__name__, val)
return val`

class Circle(object):
def __init__(self, radius):
self.radius = radius

@lazy
def area(self):
print('evalute')
return 3.14 * self.radius ** 2
all_files = []
def getAllFiles(directory_path):
import os
for sChild in os.listdir(directory_path):
sChildPath = os.path.join(directory_path,sChild)
if os.path.isdir(sChildPath):
getAllFiles(sChildPath)
else:
all_files.append(sChildPath)
return all_files
#secure_filename将字符串转化为安全的文件名
from werkzeug import secure_filename
secure_filename("My cool movie.mov") # output:My_cool_movie.mov
secure_filename("../../../etc/passwd") # output:etc_passwd
secure_filename(u'i contain cool ümläuts.txt') # output:i_contain_cool_umlauts.txt
from datetime import datetime

datetime.now().strftime("%Y-%m-%d")

import time
#这里只有localtime可以被格式化,time是不能格式化的
time.strftime("%Y-%m-%d",time.localtime())
# 会报错,但是tuple的值会改变,因为t[1]id没有发生变化
t=(1,[2,3])
t[1]+=[4,5]
# t[1]使用appendextend方法并不会报错,并可以成功执行
class Mydict(dict):
def __missing__(self,key): # 当Mydict使用切片访问属性不存在的时候返回的值
return key
# +不能用来连接列表和元祖,而+=可以(通过iadd实现,内部实现方式为extends(),所以可以增加元组),+会创建新对象
#不可变对象没有__iadd__方法,所以直接使用的是__add__方法,因此元祖可以使用+=进行元祖之间的相加
dict.fromkeys(['jim','han'],21) # output:{'jim': 21, 'han': 21}

网络知识

    204 No Content //请求成功处理,没有实体的主体返回,一般用来表示删除成功
206 Partial Content //Get范围请求已成功处理
303 See Other //临时重定向,期望使用get定向获取
304 Not Modified //求情缓存资源
307 Temporary Redirect //临时重定向,Post不会变成Get
401 Unauthorized //认证失败
403 Forbidden //资源请求被拒绝
400 //请求参数错误
201 //添加或更改成功
503 //服务器维护或者超负载
    # environ:一个包含所有HTTP请求信息的dict对象
# start_response:一个发送HTTP响应的函数
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return '<h1>Hello, web!</h1>'

Mysql

例如:
select id from t where substring(name,1,3) = 'abc' – name;
以abc开头的,应改成:
select id from t where name like 'abc%'
例如:
select id from t where datediff(day, createdate, '2005-11-30') = 0'2005-11-30';
应改为:
如:
select id from t where num/2 = 100
应改为:
select id from t where num = 100*2

Redis命令总结

Linux

设计模式

单例模式

    # 方式一
def Single(cls,*args,**kwargs):
instances = {}
def get_instance (*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@Single
class B:
pass
# 方式二
class Single:
def __init__(self):
print("单例模式实现方式二。。。")

single = Single()
del Single # 每次调用single就可以了
# 方式三(最常用的方式)
class Single:
def __new__(cls,*args,**kwargs):
if not hasattr(cls,'_instance'):
cls._instance = super().__new__(cls,*args,**kwargs)
return cls._instance

工厂模式

    class Dog:
def __init__(self):
print("Wang Wang Wang")
class Cat:
def __init__(self):
print("Miao Miao Miao")


def fac(animal):
if animal.lower() == "dog":
return Dog()
if animal.lower() == "cat":
return Cat()
print("对不起,必须是:dog,cat")

构造模式

    class Computer:
def __init__(self,serial_number):
self.serial_number = serial_number
self.memory = None
self.hadd = None
self.gpu = None
def __str__(self):
info = (f'Memory:{self.memoryGB}',
'Hard Disk:{self.hadd}GB',
'Graphics Card:{self.gpu}')
return ''.join(info)
class ComputerBuilder:
def __init__(self):
self.computer = Computer('Jim1996')
def configure_memory(self,amount):
self.computer.memory = amount
return self #为了方便链式调用
def configure_hdd(self,amount):
pass
def configure_gpu(self,gpu_model):
pass
class HardwareEngineer:
def __init__(self):
self.builder = None
def construct_computer(self,memory,hdd,gpu)
self.builder = ComputerBuilder()
self.builder.configure_memory(memory).configure_hdd(hdd).configure_gpu(gpu)
@property
def computer(self):
return self.builder.computer

数据结构和算法内置数据结构和算法

python实现各种数据结构


快速排序

    def quick_sort(_list):
if len(_list) < 2:
return _list
pivot_index = 0
pivot = _list(pivot_index)
left_list = [i for i in _list[:pivot_index] if i < pivot]
right_list = [i for i in _list[pivot_index:] if i > pivot]
return quick_sort(left) + [pivot] + quick_sort(right)

选择排序

    def select_sort(seq):
n = len(seq)
for i in range(n-1)
min_idx = i
for j in range(i+1,n):
if seq[j] < seq[min_inx]:
min_idx = j
if min_idx != i:
seq[i], seq[min_idx] = seq[min_idx],seq[i]

插入排序

    def insertion_sort(_list):
n = len(_list)
for i in range(1,n):
value = _list[i]
pos = i
while pos > 0 and value < _list[pos - 1]
_list[pos] = _list[pos - 1]
pos -= 1
_list[pos] = value
print(sql)

归并排序

    def merge_sorted_list(_list1,_list2):   #合并有序列表
len_a, len_b = len(_list1),len(_list2)
a = b = 0
sort = []
while len_a > a and len_b > b:
if _list1[a] > _list2[b]:
sort.append(_list2[b])
b += 1
else:
sort.append(_list1[a])
a += 1
if len_a > a:
sort.append(_list1[a:])
if len_b > b:
sort.append(_list2[b:])
return sort

def merge_sort(_list):
if len(list1)<2:
return list1
else:
mid = int(len(list1)/2)
left = mergesort(list1[:mid])
right = mergesort(list1[mid:])
return merge_sorted_list(left,right)

堆排序heapq模块

    from heapq import nsmallest
def heap_sort(_list):
return nsmallest(len(_list),_list)

    from collections import deque
class Stack:
def __init__(self):
self.s = deque()
def peek(self):
p = self.pop()
self.push(p)
return p
def push(self, el):
self.s.append(el)
def pop(self):
return self.pop()

队列

    from collections import deque
class Queue:
def __init__(self):
self.s = deque()
def push(self, el):
self.s.append(el)
def pop(self):
return self.popleft()

二分查找

    def binary_search(_list,num):
mid = len(_list)//2
if len(_list) < 1:
return Flase
if num > _list[mid]:
BinarySearch(_list[mid:],num)
elif num < _list[mid]:
BinarySearch(_list[:mid],num)
else:
return _list.index(num)

面试加强题:

关于数据库优化及设计

https://segmentfault.com/a/1190000018426586

缓存算法

服务端性能优化方向

上一篇 下一篇

猜你喜欢

热点阅读