Python學習過程中積累的練手程式碼片段(共12個)
阿新 • • 發佈:2020-11-04
1. 方法引數與裝飾器
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # d['王五']=12 # a=(12,12); # d[a]=123; # print(d.get((12,12))) # 關鍵字引數 # d={'張三':10,"趙四":11} # def person(name,age,**kw): # print('name:%s,age:%s,kw:%s' %(name,age,kw)) # person('張三',11,city='北京',sex='男') # person('張三',11,**d) # # 預設引數 # def person1(name,age,city='北京',sex='男'): # print('name:%s,age:%s,city:%s,sex:%s' %(name,age,city,sex)) # person1('李四',20,sex='女') # # 可變引數 # def student(*name): # print(name) # s=['張三','李四','王五'] # student(*s) # # 命名參賽 命名參賽必須傳引數名 # def peron2(name,age,*,city='北京',sex='男'): # print('name:%s,age:%s,city:%s,sex:%s' %(name,age,city,sex)) # peron2('張三',11,city='北京',sex='男') # # 在Python中定義函式,可以用必選引數、預設引數、可變引數、關鍵字引數和命名關鍵字引數, # # 這5種引數都可以組合使用。但是請注意,引數定義的順序必須是:必選引數、預設引數、可變引數、命名關鍵字引數和關鍵字引數。 # def count(): # fs = [] # for i in range(1, 4): # def f(): # return i*i # fs.append(f) # return fs # f1, f2, f3 = count() # print(f1()) # print(f2()) # print(f3()) # 裝飾器 import functools def log(text): def dis(func): @functools.wraps(func) def wrapper(*age, **kw): print('%s:%s' % (text, func.__name__)) return func(*age, **kw) return wrapper return dis @log('方法名') def sum(): print('sum') def main(): sum() if __name__ == '__main__': main()
2. 類的定義以及__getattr__實現鏈式連結
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Student(object): __slots__ = ('name', 'age') def __init__(self, name, age): self.name = name self.age = age def out(self): print('name:%s,age:%s' % (self.name, self.age)) s = Student('zs', 30) s.out() print(dir(Student)) class Chain(object): def __init__(self, path=''): self._path = path def __str__(self): return self._path def __getattr__(self, path): if 'user' != path: return Chain('%s/%s' % (self._path, path)) return lambda path: Chain('%s/%s' % (self._path, path)) print(Chain().list.user('張三').age.repo) print(type(s))
3. android自動滑動
4. 二分法查詢,選擇排序,快速排序
# 二分法查詢 def binarySearch(attr, vaule): start = 0 end = len(attr) while start <= end: middle = int((start + end) / 2) guessValue = attr[middle] if guessValue == vaule: return middle elif guessValue > vaule: end = middle else: start = middle return None # 選擇排序 def selectSort(attr): newArray = [] for i in range(len(attr)): smallIndex = selectSmall(attr) newArray.append(attr.pop(smallIndex)) return newArray def selectSmall(attr): small = attr[0] smallIndex = 0 for i in range(1, len(attr)): if attr[i] < small: small = attr[i] smallIndex = i return smallIndex # 第二種選擇排序 def selectSort2(attr): for i in range(len(attr)): selectSmall2(i, attr) def selectSmall2(start, attr): small = attr[start] smallIndex = start for i in range(start + 1, len(attr)): if attr[i] < small: small = attr[i] smallIndex = i attr[smallIndex] = attr[start] attr[start] = small # 使用遞迴求陣列的和 def recursionSum(attr): if len(attr) < 2: return attr[0] else: return attr[0] + recursionSum(attr[1:]) # 快速排序 def fastSort(attr): if len(attr) < 2: return attr else: mi = attr[0] left = [i for i in attr[1:] if i <= mi] right = [i for i in attr[1:] if i > mi] return fastSort(left) + [mi] + fastSort(right) if __name__ == '__main__': # attr = (1, 3, 6, 9, 12, 18, 19, 20, 34, 39, 40, 41, 41, 55, 56, 60, 61, 62, 63, 64, 65, 70) attr = [11, 30, 16, 29, 2, 13, 19, 24, 314, 39, 80, 101, 41, 55, 56, 60, 61, 62, 673, 14, 6, 7] # selectSort(attr) print(fastSort(attr))
5.迪克斯特拉演算法
# 迪克斯特拉演算法 # 1.建立圖 graph = {} graph["start"] = {} graph["start"]["a"] = 5 graph["start"]["b"] = 2 graph["a"] = {} graph["a"]["c"] = 4 graph["a"]["d"] = 2 graph["b"] = {} graph["b"]["a"] = 8 graph["b"]["d"] = 7 graph["c"] = {} graph["c"]["d"] = 6 graph["c"]["fin"] = 3 graph["d"] = {} graph["d"]["fin"] = 1 graph["fin"] = {} # 定義無窮大 infinity = float("inf") # 2.建立開銷表 即從起始位置到節點的開銷 costs = {} costs["a"] = 5 costs["b"] = 2 costs["c"] = infinity costs["d"] = infinity costs["fin"] = infinity # 3.建立父節點表 parents = {} parents["a"] = "start" parents["b"] = "start" parents["c"] = None parents["d"] = None parents["fin"] = None # 4.處理過的點 processed = [] # 5.找出未處理過最短路程的點 def find_lowest_cost_node(costs): lowest_cost = infinity lowest_cost_node = None for node, cost in costs.items(): if cost < lowest_cost and node not in processed: lowest_cost = cost lowest_cost_node = node return lowest_cost_node # 6.找出起點到終點最短路程 node = find_lowest_cost_node(costs) while node is not None: neighbor_nodes = graph[node] # 獲取鄰居點 cost = costs[node] # 處理點到起點的位置 for n, c in neighbor_nodes.items(): new_cost = cost + c # 從起點經過處理點的路程 if new_cost < costs[n]: # 如果經過處理點的路徑 比之前的路徑短 則更新開銷表和父節點表 costs[n] = new_cost parents[n] = node processed.append(node) node = find_lowest_cost_node(costs) result = "fin" parent = parents["fin"] while parent != "start": result = "%s-->%s" % (parent, result) parent = parents[parent] result = "start-->%s" % result print("最短路徑:%s,最短距離:%s" % (result, costs["fin"])) # ------------------------ 迪克斯特拉演算法 ------------------------- # graph = {} # 權重圖 # graph["start"] = {} # graph["start"]["a"] = 6 # graph["start"]["b"] = 2 # # graph["a"] = {} # graph["a"]["fin"] = 1 # # graph["b"] = {} # graph["b"]["a"] = 3 # graph["b"]["fin"] = 5 # # graph["fin"] = {} # # infinity = float("inf") # costs = {} # 開銷表 # costs["a"] = 6 # costs["b"] = 2 # costs["fin"] = infinity # # parents = {} # 儲存父節點 # parents["a"] = "start" # parents["b"] = "start" # parents["fin"] = None # # processed = [] # 處理過的點 # # # def find_lowest_cost_node(costs): # lowest_cost = float("inf") # lowest_cost_node = None # for node,cost in costs.items(): # if cost < lowest_cost and node not in processed: # lowest_cost = cost # lowest_cost_node = node # return lowest_cost_node # # # node = find_lowest_cost_node(costs) # while node is not None: # neighbor_nodes = graph[node] # 獲取處理節點鄰居節點 # cost = costs[node] # 獲取該節點到起點的距離 # for n in neighbor_nodes: # 迴圈鄰居節點 # new_cost = cost + neighbor_nodes[n] # 獲取經過處理該節點到鄰居節點的距離 # if costs[n] > new_cost: # costs[n] = new_cost # parents[n] = node # processed.append(node) # node = find_lowest_cost_node(costs) # lujing = "fin" # fin_ = parents["fin"] # lujing += "<-%s" % fin_ # while fin_ != "start": # fin_ = parents[fin_] # lujing += "<-%s" % fin_ # print(lujing) # print(costs["fin"]) # ------------------------ 迪克斯特拉演算法 -------------------------
6.simple_server實現簡易web
7.flask實現簡易web,支援模板
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, request, render_template app = Flask(__name__) @app.route('/', methods=['GET']) def home(): # return '<h1>Home</h1>' return render_template('Home.html') @app.route('/signin', methods=['GET']) def logon(): # return '''<form action='/logon' method='post'> # <p><input name='username'></p> # <p><input name='password' type='password'></p> # <p><button type='submit'>Log On</button></p> # </from>''' return render_template('form.html') @app.route('/signin', methods=['POST']) def toLogon(): # if request.form['username'] == 'chun' and request.form['password'] == '111111': # return '<h3>Hello,Chun</h3>' # return '<h3>Bad username or password</h3>' username = request.form['username'] password = request.form['password'] if username == 'chun' and password == '111111': return render_template('signin-ok.html', username=username) return render_template('form.html', message='Bad username or password') if __name__ == '__main__': app.run()
8. 使用asyncio,aiohttp搭建簡易web
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import asyncio from aiohttp import web from flask import Flask, request, render_template async def index(request): await asyncio.sleep(0, 5) return web.Response(body=b'''<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home</title> </head> <body> <h1>Home</h1> </body> </html>''', content_type='text/html') async def init(l): app = web.Application(loop=l) app.router.add_route('GET', '/', index) srv = await loop.create_server(app.make_handler(), '', 8000) print('Server started at http://127.0.0.1:8000...') return srv loop = asyncio.get_event_loop() loop.run_until_complete(init(loop)) loop.run_forever()
9. 上下文管理協議,with的使用
10. 簡易物件關係對映
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Field(object): """docstring for Filed""" def __init__(self, name, column_type): self.name = name self.column_type = column_type def __getattr__(self, name): pass def __str__(self): return '<%s:%s>' % (self.__class__.__name__, self.name) class StringField(Field): """docstring for StringField""" def __init__(self, name): super(StringField, self).__init__(name, 'varchar(100)') class IntegerField(Field): """docstring for IntegerField""" def __init__(self, name): super(IntegerField, self).__init__(name, 'bigint') class ModelMetaclass(type): def __new__(cls, name, bases, attrs): if (name == 'Model'): return type.__new__(cls, name, bases, attrs) print('Found model: %s' % name) mappings = dict() for k, v in attrs.items(): if isinstance(v, Field): mappings[k] = v for k in mappings.keys(): attrs.pop(k) attrs['__mappings'] = mappings attrs['__table__'] = name return type.__new__(cls, name, bases, attrs) class Model(dict, metaclass=ModelMetaclass): """docstring for Model""" def __init__(self, **kw): super(Model, self).__init__(**kw) def __getattr__(self, key): try: return self[key] except Exception as e: raise else: pass finally: pass class User(Model): name = StringField('name') email = StringField('email') address = StringField('address') id = IntegerField('id') u = User(id=1, name='張三', email='[email protected]', address='北京市') u.save()
11. 使用元類實現 namedtuple以及查詢檔案
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os # 查詢檔案 def selectFile(path, s): for root, dir_names, file_names in os.walk(path): for file_name in file_names: if s == file_name: print(os.path.abspath(os.path.join(root, file_name))) return # 使用元類實現 namedtuple # from collections import namedtuple # Point = namedtuple('Point', ['x', 'y']) def tupleC(name, attr): class Meta(type): # 定義一個元類,採用`__call__`方法來攔截類的例項化,在例項化之前我們先把位置引數全部轉入一個叫args的元組中, # 然後在呼叫type的`__call__`方法,從而把剛才的元組傳進去,這樣就只有一個引數了,從而無論你傳入多少個位置引數, # 在這個步驟之後,只會出現一個引數了,成功! def __call__(self, *args): return type.__call__(self, args) def init(self, args): if len(args) != len(attr): raise ValueError('引數數量不對') self._value = tuple(args) # self._attr=attr def _getattr(self, attr): for i, value in enumerate(attr): if value == attr: return self._value[i] return tuple.__getattr__(self, attr) def _setattr(self, attr, value): if attr != '_value' and attr != '_attr': raise ValueError('引數值不可變') tuple.__setattr__(self, attr, value) t = Meta(name, (tuple,), dict()) t.__init__ = init t.__setattr__ = _setattr t.__getattr__ = _getattr t.__str__ = lambda s: '%s%s' % (name, s._value) t.__repr__ = t.__str__ return t def main(): # selectFile('.','ShoppeVideoActivity.java') # a=os.walk('.') # next(a) # next(a) # print(next(a)) Point = tupleC('Point', ['x', 'y', 'z']) p = Point(5, 6, 1923) # p.x=10 print(p.z) print(p) if __name__ == '__main__': main()
12. 請求網路
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from urllib import request, parse from html.parser import HTMLParser from html.entities import name2codepoint # get請求 def get(): with request.urlopen('https://api.douban.com/v2/book/2129650') as f: data = f.read() print('Status:', f.status, f.reason) for k, v in f.getheaders(): print('%s:%s' % (k, v)) print('Data:', data.decode('utf-8')) def post(): print('登陸微博') email = input('Email:') passwd = input('Password:') login_data = parse.urlencode([ ('username', email), ('password', passwd), ('entry', 'mweibo'), ('client_id', ''), ('savestate', '1'), ('ec', ''), ('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F') ]) req = request.Request("https://passport.weibo.cn/sso/login") req.add_header('Origin', 'https://passport.weibo.cn') req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25') req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F') with request.urlopen(req, data=login_data.encode("utf-8")) as f: print('Status:', f.status, f.reason) for k, v in f.getheaders(): print('%s:%s' % (k, v)) print('Data:', f.read().decode('utf-8')) class MyHTMLParser(HTMLParser): def error(self, message): print('error---message:%s' % message) # Overridable -- handle start tag def handle_starttag(self, tag, attrs): print('handle_starttag---tag:%s,attrs:%s' % (tag, attrs)) # Overridable -- handle end tag def handle_endtag(self, tag): print('handle_endtag---tag:%s' % tag) # Overridable -- handle character reference def handle_charref(self, name): print('handle_charref---name:%s' % name) # Overridable -- handle entity reference def handle_entityref(self, name): print('handle_entityref---name:%s' % name) # Overridable -- handle data def handle_data(self, data): print('handle_data---data:%s' % data) # Overridable -- handle comment def handle_comment(self, data): print('handle_comment---data:%s' % data) # Overridable -- finish processing of start+end tag: <tag.../> def handle_startendtag(self, tag, attrs): MyHTMLParser.handle_startendtag(self,tag,attrs) print('handle_startendtag---tag:%s,attrs:%s' % (tag, attrs)) def getHTML(): pars=MyHTMLParser() with request.urlopen("https://www.python.org/events/python-events/") as f: result=f.read().decode('utf-8') print(result) pars.feed(result) def main(): getHTML() if __name__ == '__main__': main()
以上的12個Python小例子都是我在學習Python的過程中積累的,分享給大家,希望對正在學習Python的朋友有幫助~~