python学习之路基础篇(第六篇)
一、算法
- 冒泡排序
两两比较 打的沉下去,小的浮上来 从而把数字从小到大排列出来
- 选择排序
随机取一个索引作为最大值,然后和列表中的其他索引进行比较,如果l[0]<l[1],则将l[1]修改为最大值,继续和其他索引元素比较,将最大值排在最后,完成排序
- 插入排序
使用维护一个有序的集合,获取第一个元素作为最大值,然后去列表中的第二个元素,两两比较,如果比第二个元素大于第一个元素则排在第一个元素后面,如果小于第一个元素则排在第一个元素前面,然后依次取列表中的元素按照此方法进行比较,最终完成列表元素从小到大的排序
冒泡排序
需求:请按照从小到大对列表 [13, 22, 6, 99, 11] 进行排序
思路:相邻两个值进行比较,将较大的值放在右侧,依次比较!
li = [13, 22, 6, 99, 11] for m in range(4): # 等价于 #for m in range(len(li)-1):
if li[m]> li[m+1]:
temp = li[m+1]
li[m+1] = li[m]
li[m] = temp
li = [13, 22, 6, 99, 11] for m in range(4): # 等价于 #for m in range(len(li)-1):
if li[m]> li[m+1]:
temp = li[m+1]
li[m+1] = li[m]
li[m] = temp for m in range(3): # 等价于 #for m in range(len(li)-2):
if li[m]> li[m+1]:
temp = li[m+1]
li[m+1] = li[m]
li[m] = temp for m in range(2): # 等价于 #for m in range(len(li)-3):
if li[m]> li[m+1]:
temp = li[m+1]
li[m+1] = li[m]
li[m] = temp for m in range(1): # 等价于 #for m in range(len(li)-4):
if li[m]> li[m+1]:
temp = li[m+1]
li[m+1] = li[m]
li[m] = temp
print li
li = [13, 22, 6, 99, 11] for i in range(1,5):
for m in range(len(li)-i):
if li[m] > li[m+1]:
temp = li[m+1]
li[m+1] = li[m]
li[m] = temp
二、递归函数的应用
求7的阶乘
def func(num):
if num == 1:
return 1
return num * func(num-1) x = func(7)
print(x) # 程序运行结果如下:
# 5040
三、反射
1.反射必知必会
def f1():
print('f1') #f1和“f1”二者的区别
# f1 #函数名,是一个变量,代指整个函数
# "f1" #字符串对象
#s1.py
def func():
print('func') #index.py
import s1
s1.func() #程序运行结果:func
#程序的返回值为None
#如果函数中没有显示的return,则默认的返回值为None
2.需求:根据用户的输入的不同来展示不同页面
#commons.py
def login():
print('login') def logout():
print('logout') def home():
print('home') #index.py
import commons def run():
inp = input('请输入你要访问的页面:')
# inp = login,假设用户输入的是字符串是login,则inp = login
# commons.inp() # commons.login
if inp == 'login':
commons.login() if __name__ == "__main__":
run() #程序运行结果如下:
请输入你要访问的页面:login
login
从上面的输出可以看到,程序可以根据用户的输入来显示不同的内容,而用户的输入都是以字符串的形式存在的,我们是否可以利用用户输入的字符串对模块进行相关的操作呢?当然可以,在python中,反射就是利用字符串的实行去对象(默认)中操作(寻找)成员
#反射:getattr hasattr
#commons.py
def login():
print('login') def logout():
print('logout') def home():
print('home') #index.py
import commons
def run():
inp = input('请输入你要访问的页面:')
if hasattr(commons,inp):
func = getattr(commons,inp)
func()
else:
print('404 ERROR page!') if __name__ == "__main__":
run() #程序执行结果如下:
请输入你要访问的页面:403
404 ERROR page!
3.补充知识
__main__ #只有执行当前文件时,当前文件的特殊变量__name__=="__main__"
__file__ #当前py文件所在的路径
__cached__ #字节码存放的位置
__package__ #py文件所在的软件包
4.反射和__import__的应用
__import__:模块的导入
#manager.py
def order():
print('订单页面') #commons.py
def home():
print('首页面') #index.py
def run():
#account/login
inp = input('请输入要访问的URL:') m, f = inp.split('/') #将用户输入的内容使用/进行分隔,将模块名赋值给m,方法赋值给f
#obj = __inport__('lib.' + m,fromlist = True),如果要导入的模块和index不是同级目录,则需要对模块进行拼接,并且设置fromlist=True
obj = __import__(m)
if hasattr(obj,f):
func = getattr(obj,f)
func()
else:
print('404 error page') if __name__ == '__main__':
run() #程序运行结果如下:
请输入要访问的URL:commons/order
404 error page 请输入要访问的URL:account/login
登录页面 请输入要访问的URL:commons/home
首页面
四、加密模块hashlib
用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
import hashlib # ######## md5 ########
hash = hashlib.md5()
# help(hash.update)
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
print(hash.digest()) ######## sha1 ######## hash = hashlib.sha1()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest()) # ######## sha256 ######## hash = hashlib.sha256()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest()) # ######## sha384 ######## hash = hashlib.sha384()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest()) # ######## sha512 ######## hash = hashlib.sha512()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
import hashlib
######### md5 ########
hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8"))
hash.update(bytes('admin',encoding="utf-8"))
print(hash.hexdigest())
python内置还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密
import hmac
h = hmac.new(bytes('898oaFs09f',encoding="utf-8"))
h.update(bytes('admin',encoding='utf-8'))
print(h.hexdigest())
五、正则表达式
python中re模块提供了正则表达式相关操作
字符:
. 匹配除换行符以外的任意字符
\w 匹配字母或数字或下划线或汉字
\s 匹配任意的空白符
\d 匹配数字
\b 匹配单词的开始或结束
^ 匹配字符串的开始
$ 匹配字符串的结束
次数:
* 重复零次或更多次
+ 重复一次或更多次
? 重复零次或一次
{n} 重复n次
{n,} 重复n次或更多次
{n,m} 重复n到m次
match:从气势位置开始匹配,匹配成功返回一个对象,未匹配成功返回None
# match,从起始位置开始匹配,匹配成功返回一个对象,未匹配成功返回None match(pattern, string, flags=0)
# pattern: 正则模型
# string : 要匹配的字符串
# falgs : 匹配模式
X VERBOSE Ignore whitespace and comments for nicer looking RE's.
I IGNORECASE Perform case-insensitive matching.
M MULTILINE "^" matches the beginning of lines (after a newline)
as well as the string.
"$" matches the end of lines (before a newline) as well
as the end of the string.
S DOTALL "." matches any character at all, including the newline. A ASCII For string patterns, make \w, \W, \b, \B, \d, \D
match the corresponding ASCII character categories
(rather than the whole Unicode categories, which is the
default).
For bytes patterns, this flag is the only available
behaviour and needn't be specified. L LOCALE Make \w, \W, \b, \B, dependent on the current locale.
U UNICODE For compatibility only. Ignored for string patterns (it
is the default), and forbidden for bytes patterns.
import re #match:从字符串的开头进行匹配
#匹配成功
res = re.match(".","abc123def")
#匹配不成功
res1 = re.match("adf","abc123def")
#显示匹配的字符
res2 = re.match(".","abc123def").group()
print(res)
print(res1)
print(res2) 程序输出结果如下:
<_sre.SRE_Match object; span=(0, 1), match='a'>
None
a
search:浏览整个字符串去匹配第一个,未匹配成功返回None
# search,浏览整个字符串去匹配第一个,未匹配成功返回None
# search(pattern, string, flags=0)
#从整个字符串中进行查找一旦匹配就输出结果
res3 = re.search("\d+","abc123def456ghi")
程序执行结果入如下:
<_sre.SRE_Match object; span=(3, 6), match='123'>
#实例2
name = "Chong li"
res = re.search("(\w+)\s(\w+)",name).group()
res1 = re.search("(\w+)\s(\w+)",name).groups()
print(res)
print(res1)
# 程序执行结果:
Chong li
('Chong', 'li') #实例3
res = re.search("(?P<name>\w+)\s(?P<last_name>\w+)",name)
name = res.group("name")
xing = res.group("last_name")
print(name)
print(xing)
#程序执行结果:
Chong
li
findall:获取非重复的匹配列表,如果有一个组则以列表形式返回,且每一个匹配均是字符串,如果模型中有多个组,则以列表形式返回,且每一个匹配都是元组,空的匹配也会包含在结果中
# findall,获取非重复的匹配列表;如果有一个组则以列表形式返回,且每一个匹配均是字符串;如果模型中有多个组,则以列表形式返回,且每一个匹配均是元祖;
# 空的匹配也会包含在结果中
#findall(pattern, string, flags=0)
#实例
#匹配字符串中所有的数字
res4 = re.findall("\d+","abc123def456ghi*sdf3_def")
#匹配除数字以外的所有内容,也即针对res4取反
res5 = re.findall("[^\d+]","abc123def456ghi*sdf3_def")
res6 = re.findall("[^\d]","abc123def456ghi*sdf3_def")
print(res4)
print(res5)
print(res6) 程序执行结果如下:
['123', '456', '3']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', '*', 's', 'd', 'f', '_', 'd', 'e', 'f']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', '*', 's', 'd', 'f', '_', 'd', 'e', 'f']
sub:替换匹配成功的指定位置字符串
# sub,替换匹配成功的指定位置字符串 sub(pattern, repl, string, count=0, flags=0)
# pattern: 正则模型
# repl : 要替换的字符串或可执行对象
# string : 要匹配的字符串
# count : 指定匹配个数
# flags : 匹配模式 #字符串内容的替换
res9 = re.sub("ab","LI","abc123def456ghi*sdf3_abdef")
res10 = re.sub("ab","LI","abc123def456ghi*sdf3_abdef",count=1)
print(res9)
print(res10) 程序运行结果如下:
LIc123def456ghi*sdf3_LIdef
LIc123def456ghi*sdf3_abdef
split:根据正则匹配分隔字符串
# split,根据正则匹配分割字符串
#语法
split(pattern, string, maxsplit=0, flags=0)
# pattern: 正则模型
# string : 要匹配的字符串
# maxsplit:指定分割个数
# flags : 匹配模式
#实例
#把字符串按照数字进行分隔
res7 = re.split("\d+","abc123def456ghi*sdf3_def")
#把字符串按照数字或者*进行分隔
res8 = re.split("[\d,\*]","abc123def456ghi*sdf3_def")
print(res7)
print(res8)
#程序运行结果如下:
['abc', 'def', 'ghi*sdf', '_def']
['abc', '', '', 'def', '', '', 'ghi', 'sdf', '_def']
python学习之路基础篇(第六篇)的更多相关文章
- python学习之路基础篇(第四篇)
一.课程内容回顾 1.python基础 2.基本数据类型 (str|list|dict|tuple) 3.将字符串“老男人”转换成utf-8 s = "老男人" ret = by ...
- python学习之路基础篇(第八篇)
一.作业(对象的封装) 要点分析 1.封装,对象中嵌套对象 2.pickle,load,切记,一定要先导入相关的类二.上节内容回顾和补充 面向对象基本知识: 1.类和对象的关系 2.三大特性: 封装 ...
- python学习之路基础篇(第五篇)
前四天课程回顾 1.python简介 2.python基本数据类型 类: int:整型 | str:字符串 | list:列表 |tuple:元组 |dict:字典 | set:集合 对象: li = ...
- python学习之路基础篇(第七篇)
一.模块 configparser configparser用于处理特定格式的文件,其本质是利用open来对文件进行操作 [section1] # 节点 k1 = v1 # 值 k2:v2 # 值 [ ...
- python学习之路基础篇(三)
博客参考:http://www.cnblogs.com/wupeiqi/articles/4943406.html http://www.cnblogs.com/luotianshuai/p/4949 ...
- Python学习之路基础篇--08Python基础+ 文件的基本操作和 注册小作业
1 文件的基本操作 #1. 打开文件的模式有(默认为文本模式): r ,只读模式[默认模式,文件必须存在,不存在则抛出异常] w,只写模式[不可读:不存在则创建:存在则清空内容] a, 只追加写模式[ ...
- Python学习之路基础篇--02Python基础+小作业
1 变量 变量就是将一些运算的中间结果暂存到内存中,以便后续代码调用.必须由数字,字母,下划线任意组合,且不能数字开头.不能是python中的关键字,如['and', 'as', 'assert', ...
- Python学习之路基础篇--01Python的基本常识
1 计算机基础 首先认识什么是CPU(Central Processing Unit),即中央处理器,相当于人类的大脑.内存,临时储存数据,断电即消失.硬盘,可以长久的储存数据,有固态硬盘,机械硬盘之 ...
- python学习之路——基础篇(3)模块(续)
re正则表达式.shutil.ConfigParser.xml 一.re 正则元字符和语法: 语法 说明 表达式 完全匹配字符 字符 一般字符 匹配自身 abc abc . 匹配除换行符"\ ...
随机推荐
- O(logN)中logN的底数
转载:http://blog.csdn.net/jdbc/article/details/42173751 问题: 无论是计算机算法概论.还是数据结构书中, 关于算法的时间复杂度很多都用包含O(log ...
- python flask框架 数据库的使用
#coding:utf8 from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) # ...
- Python之进程
进程 进程(Process)是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础.在早期面向进程设计的计算机结构中,进程是程序的基本执行实体:在当代 ...
- Hibernate(十四):HQL查询(三)
背景 基于上两章节<Hibernate(十二):HQL查询(一)>.<Hibernate(十三):HQL查询(二)>,已经学习了一部分关于HQL的用法: HQL带参数查询 HQ ...
- 基于Mysql 5.7 GTID 搭建双主Keepalived 高可用
实验环境 CentOS 6.9 MySQL 5.7.18 Keepalived v1.2.13 拓扑图 10.180.2.161 M1 10.180.2.162 M2 10.180.2.200 VIP ...
- Python selenium 三种等待方式详解
1. 强制等待第一种也是最简单粗暴的一种办法就是强制等待sleep(xx),强制让闪电侠等xx时间,不管凹凸曼能不能跟上速度,还是已经提前到了,都必须等xx时间.看代码: # -*- coding: ...
- (hdu-4280)Island Transport~测试网络流模板速度~要加挂才能过啊
Problem Description In the vast waters far far away, there are many islands. People are living on th ...
- [LeetCode] Minimum Index Sum of Two Lists 两个表单的最小坐标和
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite ...
- SocketServer源码学习(二)
SocketServer 中非常重要的两个基类就是:BaseServer 和 BaseRequestHandler在SocketServer 中也提供了对TCP以及UDP的高级封装,这次我们主要通过分 ...
- 实验吧_貌似有点难(php代码审计)&头有点大
二话不说先贴代码 <?php function GetIP(){ if(!empty($_SERVER["HTTP_CLIENT_IP"])) $cip = $_SERVER ...