python常用模块
python常用模块
一 collection
python 常用 数据类型 :整型 浮点型 字符串 列表 字典 集合 元组 布尔值
具名元祖 namedtuple
from collections import namedtuple
point=namedtuple('坐标' , ['x','y','z'] ) 或者 point =namedtuple (' x' 'y' 'z')
注意的是元素个数必须跟namedtuple 第二个参数的值数量一致
print(p,p.x ,p.y ,p.z)
用具名元组来记录一个城市的信息
>>> from collections import namedtuple >>> City = namedtuple('City', 'name country population coordinates') # 第一个是类名,第二个是类的各个字段的名字。后者可以是由数个字符串组成的可迭代对象,或者是由空格分隔开的字段名组成的字符串
>>> tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667)) >>> tokyo City(name='Tokyo', country='JP', population=36.933, coordinates=(35.689722, 139.691667)) >>> tokyo.population 36.933 >>> tokyo.coordinates (35.689722, 139.691667) >>> tokyo[1] 'JP'
队列 先进先出 (FIFO first in first out )
import queue
q= queue.Queue
q.put('first')
q.put('second')
q.get()
q.get()
双端队列
deque
from collections import deque:
dq=queue(['a','b','c'])
apend apendleft
pop popleft
dq.insert(1,'插入值') 双端队列的特殊点在于可以任意位置插入值
deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:
>>> from collections import deque >>> q = deque(['a', 'b', 'c']) >>> q.append('x') >>> q.appendleft('y') >>> q deque(['y', 'a', 'b', 'c', 'x'])
deque除了实现list的append()
和pop()
外,还支持appendleft()
和popleft()
,这样就可以非常高效地往头部添加或删除元素。
有序字典
OrderedDict
from collections import OrderedDict
od=OrderedDict([(1,1),(2,2),(3,3)])
OrderedDict的key会按照插入的顺序排序 而不是元素的本身的排序
如果要保持Key的顺序,可以用OrderedDict
:
>>> 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)])
注意,OrderedDict
的Key会按照插入的顺序排列,不是Key本身排序:
>>> od = OrderedDict() >>> od['z'] = 1 >>> od['y'] = 2 >>> od['x'] = 3 >>> od.keys() # 按照插入的Key的顺序返回 ['z', 'y', 'x']
默认值字典
defauldict
使用原生dict时 如果引用的key不存在 就会抛出keyERRoR 错误 如果希望key不存在是 返回一个默认值 就可以用defaultdict
from collections import defaultdict
dd=defaultdict(lambda : 'n/a')
dd['k1']='abc'
dd['k1'] 返回abc
dd['k2'] 返回'n/a'
计数器
Counter
追踪容器中值出现的个数 ,是一个无序容器 类型,以字典的键值对 的方式储存 ,其中 元素作为key 技术作为value
技术值可以包括0和负数 类似于bags multisets
import collections
c=collections.Counter('sssasaaad')
print(c)
Counter({'s': 4, 'a': 4, 'd': 1})
二丶 time模块:
主要内容
时间戳
线程推迟 time.sleep(secs)
格式化时间
结构化时间
import time
time.time()
time.strftime('%Y-%m*%d %H:%M:%S') 年月日 时分秒
元组(struct_time) :struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天等)
索引(Index) | 属性(Attribute) | 值(Values) |
---|---|---|
0 | tm_year(年) | 比如2011 |
1 | tm_mon(月) | 1 - 12 |
2 | tm_mday(日) | 1 - 31 |
3 | tm_hour(时) | 0 - 23 |
4 | tm_min(分) | 0 - 59 |
5 | tm_sec(秒) | 0 - 60 |
6 | tm_wday(weekday) | 0 - 6(0表示周一) |
7 | tm_yday(一年中的第几天) | 1 - 366 |
8 | tm_isdst(是否是夏令时) | 默认为0 |
格式多变 链接符号任意
time.localtime() 当地时间
datatime.datatime.today()
#时间元组:localtime将一个时间戳转换为当前时区的struct_time time.localtime() time.struct_time(tm_year=2017, tm_mon=7, tm_mday=24, tm_hour=13, tm_min=59, tm_sec=37, tm_wday=0, tm_yday=205, tm_isdst=0)
小结:时间戳是计算机能够识别的时间;时间字符串是人能够看懂的时间;元组则是用来操作时间的
几种格式之间的转换
#时间戳-->结构化时间 #time.gmtime(时间戳) #UTC时间,与英国伦敦当地时间一致 #time.localtime(时间戳) #当地时间。例如我们现在在北京执行这个方法:与UTC时间相差8小时,UTC时间+8小时 = 北京时间 >>>time.gmtime(1500000000) time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=2, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0) >>>time.localtime(1500000000) time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0) #结构化时间-->时间戳 #time.mktime(结构化时间) >>>time_tuple = time.localtime(1500000000) >>>time.mktime(time_tuple) 1500000000.0
#结构化时间-->字符串时间 #time.strftime("格式定义","结构化时间") 结构化时间参数若不传,则显示当前时间 >>>time.strftime("%Y-%m-%d %X") '2017-07-24 14:55:36' >>>time.strftime("%Y-%m-%d",time.localtime(1500000000)) '2017-07-14' #字符串时间-->结构化时间 #time.strptime(时间字符串,字符串对应格式) >>>time.strptime("2017-03-16","%Y-%m-%d") time.struct_time(tm_year=2017, tm_mon=3, tm_mday=16, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=75, tm_isdst=-1) >>>time.strptime("07/24/2017","%m/%d/%Y") time.struct_time(tm_year=2017, tm_mon=7, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=205, tm_isdst=-1)
#结构化时间 --> %a %b %d %H:%M:%S %Y串 #time.asctime(结构化时间) 如果不传参数,直接返回当前时间的格式化串 >>>time.asctime(time.localtime(1500000000)) 'Fri Jul 14 10:40:00 2017' >>>time.asctime() 'Mon Jul 24 15:18:33 2017' #时间戳 --> %a %b %d %H:%M:%S %Y串 #time.ctime(时间戳) 如果不传参数,直接返回当前时间的格式化串 >>>time.ctime() 'Mon Jul 24 15:19:07 2017' >>>time.ctime(1500000000) 'Fri Jul 14 10:40:00 2017'
import time true_time=time.mktime(time.strptime('2017-09-11 08:30:00','%Y-%m-%d %H:%M:%S')) time_now=time.mktime(time.strptime('2017-09-12 11:00:00','%Y-%m-%d %H:%M:%S')) dif_time=time_now-true_time struct_time=time.gmtime(dif_time) print('过去了%d年%d月%d天%d小时%d分钟%d秒'%(struct_time.tm_year-1970,struct_time.tm_mon-1, struct_time.tm_mday-1,struct_time.tm_hour, struct_time.tm_min,struct_time.tm_sec))
datetime模块
import datetime # 自定义日期 res = datetime.date(2019, 7, 15) print(res) # 2019-07-15 # 获取本地时间 # 年月日 now_date = datetime.date.today() print(now_date) # 2019-07-01 # 年月日时分秒 now_time = datetime.datetime.today() print(now_time) # 2019-07-01 17:46:08.214170 # 无论是年月日,还是年月日时分秒对象都可以调用以下方法获取针对性的数据 # 以datetime对象举例 print(now_time.year) # 获取年份2019 print(now_time.month) # 获取月份7 print(now_time.day) # 获取日1 print(now_time.weekday()) # 获取星期(weekday星期是0-6) 0表示周一 print(now_time.isoweekday()) # 获取星期(weekday星期是1-7) 1表示周一 # timedelta对象 # 可以对时间进行运算操作 import datetime # 获得本地日期 年月日 tday = datetime.date.today() # 定义操作时间 day=7 也就是可以对另一个时间对象加7天或者减少7点 tdelta = datetime.timedelta(days=7) # 打印今天的日期 print('今天的日期:{}'.format(tday)) # 2019-07-01 # 打印七天后的日期 print('从今天向后推7天:{}'.format(tday + tdelta)) # 2019-07-08 # 总结:日期对象与timedelta之间的关系 """ 日期对象 = 日期对象 +/- timedelta对象 timedelta对象 = 日期对象 +/- 日期对象 验证: """ # 定义日期对象 now_date1 = datetime.date.today() # 定义timedelta对象 lta = datetime.timedelta(days=6) now_date2 = now_date1 + lta # 日期对象 = 日期对象 +/- timedelta对象 print(type(now_date2)) # <class 'datetime.date'> lta2 = now_date1 - now_date2 # timedelta对象 = 日期对象 +/- 日期对象 print(type(lta2)) # <class 'datetime.timedelta'> # 小练习 计算举例今年过生日还有多少天 birthday = datetime.date(2019, 12, 21) now_date = datetime.date.today() days = birthday - now_date print('生日:{}'.format(birthday)) print('今天的日期:{}'.format(tday)) print('距离生日还有{}天'.format(days)) # 总结年月日时分秒及时区问题 import datetime dt_today = datetime.datetime.today() dt_now = datetime.datetime.now() dt_utcnow = datetime.datetime.utcnow() # UTC时间与我们的北京时间cha ju print(dt_today) print(dt_now) print(dt_utcnow