collection模块:
namedtuple:它是一个函数,是用来创建一个自定义的tuple对象的,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。所以我们就可以用它来很方便的定义一种数据类型了,它具备了tuple的不可变类型,又可以根据属性来进行引用,十分的方便。
第二个元素可以传可迭代对象,也可以传字符串,但是字符串之间要以空格隔开
元素的个数必须和namedtuple的第二个参数的个数相同。
>>> from collections import namedtuple >>> Point = namedtuple('Point', ['x', 'y']) >>> p = Point(1, 2) >>> p.x 1 >>> p.y 2
deque:实现高效插入和删除操作的双向列表,适合用于队列和栈
使用list进行存储数据的时候,按索引访问元素很快,但是插入和删除元素就很慢了,因为list内部是线性存储的,当数据量很大的时候,插入和删除的效率就很低了。
>>> from collections import deque >>> q = deque(['a', 'b', 'c']) >>> q.append('x') >>> q.appendleft('y') >>> q deque(['y', 'a', 'b', 'c', 'x'])
>>> from collections import deque >>> q = deque(['a', 'b', 'c']) >>> q.pop('x') >>> q.popleft('y') >>> q deque(['b'])
deque还支持根据索引在任意位置插值:
q.insert(0, 'x')
defaultdict:当使用dict时,如果引用的key不存在的话,就会抛出KeyError的错误。如果希望key不存在的时候,返回一个默认值,这时候就可以使用defaultdict:
>>> from collections import defaultdict >>> dd = defaultdict(lambda: 'N/A') >>> dd['key1'] = 'abc' >>> dd['key1'] # key1存在 'abc' >>> dd['key2'] # key2不存在,返回默认值 'N/A'
注意:默认值是调用函数返回的,而函数在创建defaultdict对象的时候传入的(除了在Key不存在时返回默认值,他的其他行为跟dict是一样的)
OrderedDict:保持key的顺序。
>>> from collections import OrderedDict >>> d = dict([('a', 1), ('b', 2), ('c', 3)]) >>> d # dict的Key是无序的 {'a': 1, 'c': 3, 'b': 2} >>> od = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) >>> od # OrderedDict的Key是有序的 OrderedDict([('a', 1), ('b', 2), ('c', 3)])
注意:OrederedDict的Key会按照插入的顺序排列,不会按照key本身进行排列。
>>> od = OrderedDict() >>> od['z'] = 1 >>> od['y'] = 2 >>> od['x'] = 3 >>> od.keys() # 按照插入的Key的顺序返回 ['z', 'y', 'x']
OrederedDict可以实现FIFO(先进先出)的dict,当容量超出限制时,先删除最早添加的Key。
Counter:就是一个简单的计数器,统计出现的个数。
>>> from collections import Counter >>> c = Counter() >>> for ch in 'programming': ... c[ch] = c[ch] + 1 ... >>> c Counter({'g': 2, 'm': 2, 'r': 2, 'a': 1, 'i': 1, 'o': 1, 'n': 1, 'p': 1})
time模块:
三种表现形式:1、时间戳 :表示的是从1970年1月1日00:00:00开始计算的偏移量。一旦运行的话返回的是float类型
2、格式化时间(用来展示给人看的)
3、结构化时间struct_time元组共有9个元素(年、月、日、时、分、秒、一年中第几周、一年中第几天、夏令时)
import time print(time.time()) # 时间戳 print(time.strftime('%Y-%m-%d')) # 格式化的时间字符串 print(time.strftime('%Y-%m-%d %H:%M:%S')) print(time.strftime('%Y-%m-%d %X')) # %X等价于%H:%M:%S print(time.strftime('%H:%M')) print(time.strftime('%Y/%m')) print(time.localtime()) # 本地区的struct_time print(time.localtime(time.time())) res = time.localtime(time.time()) print(time.time()) print(time.mktime(res)) # 将一个struct_time转化为时间戳 print(time.strftime('%Y-%m',time.localtime())) print(time.strptime(time.strftime('%Y-%m',time.localtime()),'%Y-%m'))
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
%a Locale’s abbreviated weekday name. %A Locale’s full weekday name. %b Locale’s abbreviated month name. %B Locale’s full month name. %c Locale’s appropriate date and time representation. %d Day of the month as a decimal number [01,31]. %H Hour (24-hour clock) as a decimal number [00,23]. %I Hour (12-hour clock) as a decimal number [01,12]. %j Day of the year as a decimal number [001,366]. %m Month as a decimal number [01,12]. %M Minute as a decimal number [00,59]. %p Locale’s equivalent of either AM or PM. (1) %S Second as a decimal number [00,61]. (2) %U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (3) %w Weekday as a decimal number [0(Sunday),6]. %W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3) %x Locale’s appropriate date representation. %X Locale’s appropriate time representation. %y Year without century as a decimal number [00,99]. %Y Year with century as a decimal number. %z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59]. %Z Time zone name (no characters if no time zone exists). %% A literal '%' character.
其中计算机认识的只能是时间戳格式,而程序员可处理的或者说是人类能看懂的时间格式:格式化的时间字符串、结构化的时间,于是就有了下图。
1 #--------------------------转换时间 2 # localtime([secs]) 3 # 将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。 4 time.localtime() 5 time.localtime(1473525444.037215) 6 7 # gmtime([secs]) 和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。 8 9 # mktime(t) : 将一个struct_time转化为时间戳。 10 print(time.mktime(time.localtime()))#1473525749.0 11 12 13 # strftime(format[, t]) : 把一个代表时间的元组或者struct_time(如由time.localtime()和 14 # time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。如果元组中任何一个 15 # 元素越界,ValueError的错误将会被抛出。 16 print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56 17 18 # time.strptime(string[, format]) 19 # 把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。 20 print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X')) 21 #time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6, 22 # tm_wday=3, tm_yday=125, tm_isdst=-1) 23 #在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"。
其它的用法:
sleep(secs) # 线程推迟指定的时间运行,单位是秒
datetime模块:
#时间加减 import datetime print(datetime.datetime.now()) #返回当前时间 #print(datetime.date.fromtimestamp(time.time()) ) # 时间戳直接转成日期格式 2019-07-18 print(datetime.datetime.now() ) print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天 print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天 print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时 print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分 c_time = datetime.datetime.now() print(c_time.replace(minute=3,hour=2)) #时间替换
random模块:
import random print(random.random())#(0,1)----float 大于0且小于1之间的小数 print(random.randint(1,3)) #[1,3] 大于等于1且小于等于3之间的整数 print(random.randrange(1,3)) #[1,3) 大于等于1且小于3之间的整数 print(random.choice([1,'23',[4,5]]))#1或者23或者[4,5] print(random.sample([1,'23',[4,5]],2))#列表元素任意2个组合 print(random.uniform(1,3))#大于1小于3的小数,如1.927109612082716 item=[1,3,5,7,9] random.shuffle(item) #打乱item的顺序,相当于"洗牌" print(item)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import random def make_code(n): res='' for i in range(n): s1 = chr(random.randint(65,90)) s2 = str(random.randint(0,9)) s3 = chr(random.randint(97,122)) res += random.choice([s1, s2, s3]) return res print(make_code(9))
os模块:跟操作系统打交道的模块
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd os.curdir 返回当前目录: ('.') os.pardir 获取当前目录的父目录字符串名:('..') os.makedirs('dirname1/dirname2') 可生成多层递归目录 os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推 os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirname os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印 os.remove() 删除一个文件 os.rename("oldname","newname") 重命名文件/目录 os.stat('path/filename') 获取文件/目录信息 os.sep 输出操作系统特定的路径分隔符,win下为"\",Linux下为"/" os.linesep 输出当前平台使用的行终止符,win下为" ",Linux下为" " os.pathsep 输出用于分割文件路径的字符串 win下为;,Linux下为: os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix' os.system("bash command") 运行shell命令,直接显示 os.environ 获取系统环境变量 os.path.abspath(path) 返回path规范化的绝对路径 os.path.split(path) 将path分割成目录和文件名二元组返回 os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素 os.path.basename(path) 返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素 os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False os.path.isabs(path) 如果path是绝对路径,返回True os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略 os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间 os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间 os.path.getsize(path) 返回path的大小
在Linux和Mac平台上,该函数会原样返回path,在windows平台上会将路径中所有字符转换为小写,并将所有斜杠转换为反斜杠。 >>> os.path.normcase('c:/windows\system32\') 'c:\windows\system32\' 规范化路径,如..和/ >>> os.path.normpath('c://windows\System32\../Temp/') 'c:\windows\Temp' >>> a='/Users/jieli/test1/\a1/\\aa.py/../..' >>> print(os.path.normpath(a)) /Users/jieli/test1
os的路径处理:os.path.dirname(os.path.abspath)
sys模块:
1 sys.argv 命令行参数List,第一个元素是程序本身路径 2 sys.exit(n) 退出程序,正常退出时exit(0) 3 sys.version 获取Python解释程序的版本信息 4 sys.maxint 最大的Int值 5 sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 6 sys.platform 返回操作系统平台名称
json模块:
之前我们学习过用eval内置方法可以将一个字符串转成python对象,不过,eval方法是有局限性的,对于普通的数据类型,json.loads和eval都能用,但遇到特殊类型的时候,eval就不管用了,所以eval的重点还是通常用来执行一个字符串表达式,并返回表达式的值。
什么是序列化:
我们将对象(变量)从内存中变成可存储或传输的过程称之为序列化
为什么要序列化:
1、持久保存状态
2、跨平台数据交互
1 import json 2 3 dic={'name':'alvin','age':23,'sex':'male'} 4 print(type(dic))#<class 'dict'> 5 6 j=json.dumps(dic) 7 print(type(j))#<class 'str'> 8 9 10 f=open('序列化对象','w') 11 f.write(j) #-------------------等价于json.dump(dic,f) 12 f.close() 13 #-----------------------------反序列化<br> 14 import json 15 f=open('序列化对象') 16 data=json.loads(f.read())# 等价于data=json.load(f)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import json #dct="{'1':111}"#json 不认单引号 #dct=str({"1":111})#报错,因为生成的数据还是单引号:{'one': 1} dct='{"1":"111"}' print(json.loads(dct)) #conclusion: # 无论数据是怎样创建的,只要满足json格式,就可以json.loads出来,不一定非要dumps的数据才能loads
pickle模块:
1 import pickle 2 3 dic={'name':'alvin','age':23,'sex':'male'} 4 5 print(type(dic))#<class 'dict'> 6 7 j=pickle.dumps(dic) 8 print(type(j))#<class 'bytes'> 9 10 11 f=open('序列化对象_pickle','wb')#注意是w是写入str,wb是写入bytes,j是'bytes' 12 f.write(j) #-------------------等价于pickle.dump(dic,f) 13 14 f.close() 15 #-------------------------反序列化 16 import pickle 17 f=open('序列化对象_pickle','rb') 18 19 data=pickle.loads(f.read())# 等价于data=pickle.load(f) 20 21 22 print(data['age'])
pickle的问题和所有编程语言特有的序列化问题一样,就是它只能应用在python上,并且可能不同版本的python彼此都不兼容,因此,只能用pickle保存那些不是很重要的数据,不能成功反序列化也没有多大关系。