python_day06 匿名函数与内置函数 常用模块
匿名函数与内置函数
常用模块
1、匿名函数与内置函数
内置函数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
内置函数 bool值为假的情况:None,空,0,False print(abs(-1)) #取绝对值 all()所有可迭代对象内元素为真,结果为真。 print(all([1,2,'a',None])) #False print(all([])) #True any()有一个可迭代对象内元素为真,结果为真。 print(any([])) #False print(any([' ',None,False])) #True print(any(['',None,False])) #False print(any(['',None,False,1])) #True bin,oct,hex 二/八/十进制 print(bin(10)) print(oct(10)) print(hex(10)) bytes字节 unicode----encode----->bytes print('hello'.encode('utf-8')) print(bytes('hello',encoding='utf-8')) callable 判断是否可调用,可调用的目前学过的是函数。 print(callable(bytes)) print(callable(abs)) chr,ord ASCII编码表一一对应 print(chr(65)) #A print(chr(90)) #Z print(ord('#')) 内置函数,又被称为工厂函数 int x=1 #x=int(1) print(type(x)) x=int(2) complex #复数 float #浮点型 str list tuple dict set #可变集合 frozenset #不可变集合 s={1,2,3,4} #s=set({1,2,3,4}) print(type(s)) s1=frozenset({1,2,3,4}) print(type(s1)) dir #dir(sys) 列出sys可调用哪些属性 import sys sys.path sys.argv print(dir(sys)) divmod 商和余数的小元组 print(divmod(10,3)) #(3,1) print(divmod(102,20)) #(5,2) enumerate l=['a','b','c'] res=enumerate(l) #迭代器 for i in res: print(i) for index,item in enumerate(l): print(index,item) globals,locals #查看全局作用域和局部作用域 print(globals()) hash #hash函数 print(hash('abcdefg123')) print(hash('abcdefg123')) 给函数加文档解释,用到单引号,双引号,三引号 def func(): ''' test function :return: ''' pass print(help(func)) #列出函数的注释信息 id:是python解释器实现的功能,只是反映了变量在内存的地址 但并不是真实的内存地址 x=1 print(id(x))def func():passprint(id(func))print(func)isinstancex=1print(type(x) is int)print(isinstance(x,int)) #判断x是不是int实例x=int(1)迭代器iternextlenmaxprint(max([1,2,3,10]))print(max(['a','b']))print(min([1,2,3,10]))powprint(pow(3,2,2)) #3**2%2rangerepr,strprint(type(str(1)))print(type(repr(1))) #==str 转换为strreversedl=[1,'a',2,'c']print(list(reversed(l)))print(l)slice #切割l=[1,2,3,4,5,6]print(l[0:4:2])s=slice(0,4,2)print(l[s])sorted #排序l=[1,10,4,3,-1]print(sorted(l,reverse=True))sumprint(sum([1, 2,3]))print(sum(i for i in range(10)))varsimport m1print(vars(m1) == m1.__dict__)zip:拉链s='hellosssssssssssssssss'l=[1,2,3,4,5]print(list(zip(s,l)))__import__ #需求来自于用户交互字符串方式导入模块import sysm_name=input('module>>: ')if m_name == 'sys': m=__import__(m_name) print(m) print(m.path)sys=__import__('sys')print(sys)round #留小数点print(round(3.565,2)) #3.56print(round(3.555,2)) #3.56filter,map,reduce 重点面向对象objectsuper__dict__isinstanceissubclassclassmethodstaticmethodpropertydelattrhasattrsetattrgetattr了解compileevalexec
匿名函数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def func(x,y,z=1): return x+y+z print(func) print(func(1,2,3)) 匿名函数:1. 没有名字 2:函数体自带return print(lambda x,y,z=1:x+y+z) f=lambda x,y,z=1:x+y+z print(f) print(f(1,2,3)) 匿名函数与变量关系类似 x=1 1 print(x) print(1) 匿名函数的应用场景: 应用于一次性的场景,临时使用
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
匿名函数 lambda x,y,z=1:x+y+z #省略了return 特点:1、没有名字。2、函数体自带return 应用场景:应用于一次性的场景,临时使用。 与匿名函数结合使用 max,min,sorted 获得薪资最高的人名 salaries={ 'egon':3000, 'alex':100000000, 'wupeiqi':10000, 'yuanhao':2000 } print(max(salaries)) #yuanhao 按照字母排列顺序列出 print(max(salaries.values())) #100000000 得到结果为数字 验证print(max(salaries))的字母排序结果 t1=(1,'h',3,4,5,6) t2=(1,'y',3) print(t1 > t2) t1=(10000000,'alex') t2=(3000,'egon') print(t1 > t2) 使用拉链函数可得到最高工资人员 print(max(zip(salaries.values(),salaries.keys()))[1]) 使用max的key关键字可得到最高工资人员 def get_value(name): return salaries[name] print(max(salaries,key=get_value)) l=[] for name in salaries: res=get_value(name) l.append(res) print(max(l)) 使用max的key关键字可得到最高工资人员 key关键字使用lambda函数 lambda name:salaries[name] print(max(salaries,key=lambda name:salaries[name])) print(min(salaries,key=lambda name:salaries[name])) salaries={ 'egon':3000, 'alex':100000000, 'wupeiqi':10000, 'yuanhao':2000 } def get_value(name): return salaries[name] print(sorted(salaries)) print(sorted(salaries,key=get_value)) print(sorted(salaries,key=get_value,reverse=True)) filter,map,reduce names=['alex','wupeiqi','yuanhao','yanglei','egon'] res=map(lambda x:x if x == 'egon' else x+'SB',names) print(res) print(list(res)) def my_map(func,seq): for item in seq: yield func(item) res1=my_map(lambda x:x+'_SB',names) print(next(res1)) print(next(res1)) print(next(res1)) from functools import reduce print(reduce(lambda x,y:x+y,range(101),100)) print(reduce(lambda x,y:x+y,range(101))) l=[1,2,'a','b',3,'c','d'] filter函数 names=['alex_SB','wupeiqi_SB','yuanhao_SB','yanglei_SB','egon'] print(list(filter(lambda name:name.endswith('SB'),names)))
cmd='print(x)' x=1 eval(cmd,{'x':0},{'x':10000000}) eval(cmd,{'x':0},{'y':10000000}) s='for i in range(10):print(i,x)' code=compile(s,'','exec') print(code) exec(code,{},{'x':1111})
常用模块
正则模块:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import re print(re.findall('\w','hello_ | egon 123')) print(re.findall('\W','hello_ | egon 123')) print(re.findall('\s','hello_ | egon 123 \n \t')) print(re.findall('\S','hello_ | egon 123 \n \t')) print(re.findall('\d','hello_ | egon 123 \n \t')) print(re.findall('\D','hello_ | egon 123 \n \t')) print(re.findall('h','hello_ | hello h egon 123 \n \t')) # print(re.findall('\Ahe','hello_ | hello h egon 123 \n \t')) print(re.findall('^he','hello_ | hello h egon 123 \n \t')) # print(re.findall('123\Z','hello_ | hello h egon 123 \n \t123')) print(re.findall('123$','hello_ | hello h egon 123 \n \t123')) print(re.findall('\n','hello_ | hello h egon 123 \n \t123')) print(re.findall('\t','hello_ | hello h egon 123 \n \t123')) . [] [^] .本身代表任意一个字符 print(re.findall('a.c','a a1c a*c a2c abc a c aaaaaac aacc')) a.c print(re.findall('a.c','a a1c a*c a2c abc a\nc',re.DOTALL)) print(re.findall('a.c','a a1c a*c a2c abc a\nc',re.S)) []内部可以有多个字符,但是本身只配多个字符中的一个 print(re.findall('a[0-9][0-9]c','a a12c a1c a*c a2c a c a\nc',re.S)) print(re.findall('a[a-zA-Z]c','aac abc aAc a12c a1c a*c a2c a c a\nc',re.S)) print(re.findall('a[^a-zA-Z]c','aac abc aAc a12c a1c a*c a2c a c a\nc',re.S)) print(re.findall('a[\+\/\*\-]c','a-c a+c a/c aac abc aAc a12c a1c a*c a2c a c a\nc',re.S)) \:转义 print(re.findall(r'a\\c','a\c abc')) #rawstring ? * + {}:左边有几个字符,如果有的话,贪婪匹配 ?左边那一个字符有0个或者1个 print(re.findall('ab?','aab a ab aaaa')) ab? *左边那一个字符有0个或者无穷个 print(re.findall('ab*','a ab abb abbb abbbb bbbbbb')) print(re.findall('ab{0,}','a ab abb abbb abbbb bbbbbb')) +左边那一个字符有1个或者无穷个 print(re.findall('ab+','a ab abb abbb abbbb bbbbbb')) print(re.findall('ab{1,}','a ab abb abbb abbbb bbbbbb')) {n,m}左边的字符有n-m次 print(re.findall('ab{3}','a ab abb abbb abbbb bbbbbb')) print(re.findall('ab{2,3}','a ab abb abbb abbbb bbbbbb')) .* .*? .*贪婪匹配 print(re.findall('a.*c','a123c456c')) .*?非贪婪匹配 print(re.findall('a.*?c','a123c456c')) | print(re.findall('company|companies','Too many companies have gone bankrupt, and the next one is my company')) company|companies print(re.findall('compan|companies','Too many companies have gone bankrupt, and the next one is my company')) ():分组 print(re.findall('ab+','abababab123')) print(re.findall('ab+123','abababab123')) print(re.findall('ab','abababab123')) print(re.findall('(ab)','abababab123')) print(re.findall('(a)b','abababab123')) print(re.findall('a(b)','abababab123')) print(re.findall('(ab)+','abababab123')) print(re.findall('(?:ab)+','abababab123')) print(re.findall('(ab)+123','abababab123')) print(re.findall('(?:ab)+123','abababab123')) print(re.findall('(ab)+(123)','abababab123')) print(re.findall('compan(y|ies)','Too many companies have gone bankrupt, and the next one is my company')) print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company')) re的其他方法 print(re.findall('ab','abababab123')) print(re.search('ab','abababab123').group()) print(re.search('ab','12aasssdddssssssss3')) print(re.search('ab','12aasssdddsssssssab3sssssss').group()) print(re.search('ab','123ab456')) print(re.match('ab','123ab456')) #print(re.search('^ab','123ab456')) print(re.split('b','abcde')) print(re.split('[ab]','abcde')) print(re.sub('alex','SB','alex make love alex alex',1)) print(re.subn('alex','SB','alex make love alex alex',1)) print(re.sub('(\w+)(\W+)(\w+)(\W+)(\w+)',r'\5\2\3\4\1','alex make love')) print(re.sub('(\w+)( .* )(\w+)',r'\3\2\1','alex make love')) obj=re.compile('\d{2}') print(obj.search('abc123eeee').group()) #12 print(obj.findall('abc123eeee')) #12 print(re.findall('\-?\d+\.?\d+',"1-12*(60+(-40.35/5)-(-4*3))")) print(re.findall('\-?\d+\.?\d*',"1-12*(60+(-40.35/5)-(-4*3))")) print(re.findall('\-?\d+\.\d+',"1-12*(60+(-40.35/5)-(-4*3))")) print(re.findall('\-?\d+',"1-12*(60+(-40.35/5)-(-4*3))")) print(re.findall('\-?\d+\.\d+|(\-?\d+)',"1-12*(60+(-40.35/5)-(-4*3))")) print(re.findall('\-?\d+\.\d+|\-?\d+',"1-12*(60+(-40.35/5)-(-4*3))")) print(re.findall('\-?\d+|\-?\d+\.\d+',"1-12*(60+(-40.35/5)-(-4*3))"))
时间模块
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import time print(time.time()) print(time.strftime('%Y-%m-%d %X')) print(time.localtime()) print(time.gmtime()) #UTC print(time.localtime().tm_mon) print(time.localtime(123123123)) print(time.gmtime(123123123)) print(time.mktime(time.localtime())) print(time.strftime('%Y',time.gmtime())) '2017-03-01' print(time.strptime('2017-03-01','%Y-%m-%d')) print(time.ctime(12312312)) print(time.asctime(time.gmtime()))
random模块
import random
print(random.sample([1,'23',[4,5]],2))
print(random.uniform(1,3))
item=[1,3,5,7,9]
random.shuffle(item)
print(item)
产生随机验证码
def make_code(n):
res=''
for i in range(n):
s1=str(random.randint(0,9))
s2=chr(random.randint(65,90))
res+=random.choice([s1,s2])
return res
print(make_code(10)
os模块
import os print(os.listdir('.')) print(os.stat('m1.py').st_size) print(os.sep) print(os.linesep) print(os.pathsep) print([os.sep,os.linesep,os.pathsep]) res=os.system('dir .') print('====?>',res) print(os.path.dirname(r'C:\a\b\c\d\a.txt')) print(os.path.basename(r'C:\a\b\c\d\a.txt')) print(os.path.split(r'C:\a\b\c\d\a.txt')) print(os.stat('m1.py').st_atime) print(os.stat('m1.py').st_size) print(os.path.getsize('m1.py')) print(os.path.join('C:\\','a','b','c','d.txt')) print(os.path.join('C:\\','a','b','D:\\','c','d.txt')) print(os.path.normcase('c:/wiNdows\\system32\\') ) print(os.path.normpath('c://wIndows\\System32\\../Temp/') ) a='/Users/jieli/test1/\\\a1/\\\\aa.py/../..' print(os.path.normpath(a)) print(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) BASE_DIR=os.path.normpath(os.path.join( os.path.abspath(__file__), '..', '..' ) ) print(BASE_DIR)
sys模块
import sys,time
for i in range(1,100):
sys.stdout.write('\r%s' %('#'*i))
sys.stdout.flush()
time.sleep(0.5)
for i in range(1,100):
print('\r%s' %('#'*i),file=sys.stdout,flush=True,end='')
time.sleep(0.01)
#进度条:
print('<%s>' %'hello')
print('<%-10s>' %'hello')
print('<%-10s>' %'helloe')
print('<%-10s>' %'helloee')
print('<%-10s>' %'#')
print('<%-10s>' %'##')
print('<%-10s>' %'###')
print('<%-10s>' %'####')
print('<%-10s>' %'#####')
print('<%-10s>' %'helloee')
width=20
print('<%%-%ds>' %width) #<%-10s>
print(('<%%-%ds>' %width) %('hello'))
<%-10s> %('hello')
width=20
print(('[%%-%ds]' %width) %('#'))
print(('[%%-%ds]' %width) %('##'))
print(('[%%-%ds]' %width) %('###'))
def progress(percent,width=50): #51
if percent >= 100:
# print('\r[%s] 100%%' %(width*'#'))
percent=100
show_str=('[%%-%ds]' %width) %(int(width*percent/100)*'#')
print('\r%s %d%%' %(show_str,percent),file=sys.stdout,flush=True,end='')
total_size=1025121
recv_size=0
while recv_size < total_size:
time.sleep(0.01) #模拟下载的网络延迟
recv_size+=1024
recv_per=int(100*recv_size/total_size)
progress(recv_per,width=10)
json序列化
import json
dic={'name':'egon','age':18}
print(type(json.dumps(dic)))
with open('a.json','w') as f:
f.write(json.dumps(dic))
with open('a.json','r') as f:
data=f.read()
dic=json.loads(data)
print(dic['name'])
dic={'name':'egon','age':18}
json.dump(dic,open('b.json','w'))
print(json.load(open('b.json','r'))['name'])
with open('c.json','r') as f:
data=f.read()
#[null,true,false,1]
eval(data)
pikcle序列化
import pickle
dic={'name':'egon','age':18}
print(pickle.dumps(dic))
with open('d.pkl','wb') as f:
f.write(pickle.dumps(dic))
with open('d.pkl','rb') as f:
dic=pickle.loads(f.read())
print(dic['name'])
dic={'name':'egon','age':18}
pickle.dump(dic,open('e.pkl','wb'))
print(pickle.load(open('e.pkl','rb'))['name'])
def func():
print('from func')
import json
print(json.dumps(func))
import pickle
print(pickle.dumps(func))
pickle.dump(func,open('func.pkl','wb'))
pikcle反序列化
import pickle
def func():
print('反序列化的文件')
pickle.dump(func,open('func.pkl','wb'))
f=pickle.load(open('func.pkl','rb'))
print(f)
class Foo:
pass
obj1=Foo()
obj2=Foo()
print(obj1 is obj2)
pickle.dump(obj1,open('class.pkl','wb'))
import pickle
pickle.load(open('class.pkl','rb'))
l1=list()
l2=list()
print(type(l1))
print(type(l2))
shevel模块
import shelve
f=shelve.open(r'sheve.shl')
f['alex']={'age':28,'pwd':'alex3714'}
f['egon']={'age':18,'pwd':'3714'}
f.close()
反序列化
import shelve
obj=shelve.open(r'sheve.shl')
print(obj['alex'])
print(obj['egon'])
obj.close()
for i in obj:
print(i,obj[i])