一、算法

  • 冒泡排序

  两两比较 打的沉下去,小的浮上来  从而把数字从小到大排列出来

  • 选择排序

  随机取一个索引作为最大值,然后和列表中的其他索引进行比较,如果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学习之路基础篇(第六篇)的更多相关文章

  1. python学习之路基础篇(第四篇)

    一.课程内容回顾 1.python基础 2.基本数据类型  (str|list|dict|tuple) 3.将字符串“老男人”转换成utf-8 s = "老男人" ret = by ...

  2. python学习之路基础篇(第八篇)

    一.作业(对象的封装) 要点分析 1.封装,对象中嵌套对象 2.pickle,load,切记,一定要先导入相关的类二.上节内容回顾和补充 面向对象基本知识: 1.类和对象的关系 2.三大特性: 封装 ...

  3. python学习之路基础篇(第五篇)

    前四天课程回顾 1.python简介 2.python基本数据类型 类: int:整型 | str:字符串 | list:列表 |tuple:元组 |dict:字典 | set:集合 对象: li = ...

  4. python学习之路基础篇(第七篇)

    一.模块 configparser configparser用于处理特定格式的文件,其本质是利用open来对文件进行操作 [section1] # 节点 k1 = v1 # 值 k2:v2 # 值 [ ...

  5. python学习之路基础篇(三)

    博客参考:http://www.cnblogs.com/wupeiqi/articles/4943406.html http://www.cnblogs.com/luotianshuai/p/4949 ...

  6. Python学习之路基础篇--08Python基础+ 文件的基本操作和 注册小作业

    1 文件的基本操作 #1. 打开文件的模式有(默认为文本模式): r ,只读模式[默认模式,文件必须存在,不存在则抛出异常] w,只写模式[不可读:不存在则创建:存在则清空内容] a, 只追加写模式[ ...

  7. Python学习之路基础篇--02Python基础+小作业

    1 变量 变量就是将一些运算的中间结果暂存到内存中,以便后续代码调用.必须由数字,字母,下划线任意组合,且不能数字开头.不能是python中的关键字,如['and', 'as', 'assert', ...

  8. Python学习之路基础篇--01Python的基本常识

    1 计算机基础 首先认识什么是CPU(Central Processing Unit),即中央处理器,相当于人类的大脑.内存,临时储存数据,断电即消失.硬盘,可以长久的储存数据,有固态硬盘,机械硬盘之 ...

  9. python学习之路——基础篇(3)模块(续)

    re正则表达式.shutil.ConfigParser.xml 一.re 正则元字符和语法: 语法 说明 表达式 完全匹配字符 字符 一般字符 匹配自身 abc abc . 匹配除换行符"\ ...

随机推荐

  1. JSON(五)——同步请求中使用JSON格式字符串进行交互(不太常见的用法)

    在同步请求中使用JSON格式进行数据交互的场景并不多,同步请求是浏览器直接与服务器进行数据交互的大多是用jsp的标签jstl和el表达式对请求中的数据进行数据的渲染.我也是在一次开发中要从其它服务器提 ...

  2. Hive函数:LAG,LEAD,FIRST_VALUE,LAST_VALUE

    参考自大数据田地:http://lxw1234.com/archives/2015/04/190.htm 测试数据准备: create external table test_data ( cooki ...

  3. Object.prototype.toString.call(obj)使用方法以及原理

    这几天看vue-router的源码 发现了Object.prototype.toString.call()这样的用法,当时以为这就是转成字符串的用的,但是越看越觉得不太对劲,赶紧查查资料,一查才知道没 ...

  4. Python面向对象——重写与Super

    1本文的意义 如果给已经存在的类添加新的行为,采用继承方案 如果改变已经存在类的行为,采用重写方案 2图解继承.重写与Super 注:上面代码层层关联.super()可以用到任何方法里进行调用,本文只 ...

  5. win7安装JDK6

    注:虽然9已经出来了,但是今天刚好业务需要要装JDK6,所以以JDK 6作为演示,同样适用于JDK 7.8的安装. 安装 基本上一直点下一步就可以. 此处可修改安装路径. 我将JDK的安装路径设置成了 ...

  6. JavaScript, 函数是实现异步的基础

    昨天一朋友和我聊到JS中的异步和同步, 后来从异步和同步的问题中得出了函数的另一面, 觉得挺不错, 特此分享一下 ==== 追梦子: 聊天是同步还是异步 小A: 异步 小A: 和你聊还可以和别人聊 追 ...

  7. C#生成MD5码

    /// <summary> /// 获取文件的MD5码 /// </summary> /// <param name="fileName">传入 ...

  8. css befroe after 尾类技术器

    CSS counter计数器(content目录序号自动递增)详解 这篇文章发布于 2014年08月26日,星期二,15:54,归类于 css相关. 阅读 44148 次, 今日 11 次 by zh ...

  9. C# 获取字符串中的英文字母

    string str20 = "ABC123"; string strSplit1,strSplit2; //取出字符串中所有的英文字母 strSplit1 = Regex.Rep ...

  10. 使用tkinter加载png,jpg

    最近来使用tkinter加载图片时遇到了困难,按照资料写了 photo = PhotoImage(file='ques.png') imglabel = Label(root, image=photo ...