collections&time&random模块
一、collections模块
在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等。
1.namedtuple: 生成可以使用名字来访问元素内容的tuple
2.deque: 双端队列,可以快速的从另外一侧追加和推出对象
3.Counter: 计数器,主要用来计数
4.OrderedDict: 有序字典
5.defaultdict: 带有默认值的字典
namedtuple
from collections import namedtuple
Point=namedtuple('point',['x','y'])
p=Point(1,2)
print(p) #point(x=1, y=2)
print(p.x)
print #
from collections import namedtuple
Circle=namedtuple('circle',['x','y','r'])
c=Circle(1,2,3)
print(c) #circle(x=1, y=2, r=3)
deque
from collections import deque
q=deque(['a','b','c'])
q.append('x') #从后面放数据
q.appendleft('y') #从前面放入数据
print(q) #deque(['y', 'a', 'b', 'c', 'x']) q.insert(1,'ab')
print(q) #deque(['y', 'ab', 'a', 'b', 'c', 'x'])
print(q.pop()) #x,从后面取数据
print(q.popleft()) #y,从前面取数据
OrderedDict
from collections import OrderedDict
d=dict([('a',1),('b',2),('c',3)]) #创建列表的另一种方法
print(d)
D=OrderedDict([('a',1),('b',2),('c',3)])
print(D)
for i in D:
print(i)
#结果:a,b,c D是可迭代的 od=OrderedDict()
od['a']=5
od['b']=1
od['c']=2
print(od) #OrderedDict([('a', 5), ('b', 1), ('c', 2)]),OrderedDict的Key会按照插入的顺序排列,不是Key本身排序;
defaultdict
before:
values=[11, 22, 33,44,55,66,77,88,99,90]
my_dict={}
for i in values:
if i>66:
if 'k1' in my_dict.keys():
my_dict['k1'].append(i)
else:
my_dict['k1']=[i]
else:
if 'k2' in my_dict.keys():
my_dict['k2'].append(i)
else:
my_dict['k2']=[i]
print(my_dict) #结果:{'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]} after:
from collections import defaultdict
values = [11, 22, 33,44,55,66,77,88,99,90]
my_dict=defaultdict(list)
for value in values:
if value>66:
my_dict['k1'].append(value)
else:
my_dict['k2'].append(value)
print(my_dict) #defaultdict(<class 'list'>, {'k1': [77, 88, 99, 90], 'k2': [11, 22, 33, 44, 55, 66]}) #defaultdict为一个不存在的键提供默认值,从而避免KeyError异常.
Counter
from collections import Counter
c = Counter('abcdeabcdabcaba')
print(c) #Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1}) Counter它是一个无序的容器类型,以字典的键值对形式存储,其中元素作为key,其计数作为value。
二、time模块
在Python中,通常有这三种方式来表示时间:时间戳、元组(struct_time)、格式化的时间字符串。
(1)时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
(2)格式化的时间字符串(Format String): ‘1999-12-06’
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31) %H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59) %a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身
(3)元组(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 |
import time
print(time.time()) #1546005206.1939626 print(time.strftime("%Y-%m-%d %X")) #2018-12-28 21:53:36 ret=time.time()
print(time.localtime(ret))
# 结果:time.struct_time(tm_year=2018, tm_mon=12, tm_mday=28, tm_hour=20, tm_min=26, tm_sec=37, tm_wday=4, tm_yday=362, tm_isdst=0) #时间戳--->结构化时间
print(time.localtime(100000000)) #当地时间。例如我们现在在北京执行这个方法:与UTC时间相差8小时,UTC时间+8小时 = 北京时间
print(time.gmtime(100000000)) #UTC时间,与英国伦敦当地时间一致
#结果:
time.struct_time(tm_year=1973, tm_mon=3, tm_mday=3, tm_hour=17, tm_min=46, tm_sec=40, tm_wday=5, tm_yday=62, tm_isdst=0)
time.struct_time(tm_year=1973, tm_mon=3, tm_mday=3, tm_hour=9, tm_min=46, tm_sec=40, tm_wday=5, tm_yday=62, tm_isdst=0) #结构化时间--->时间戳
ret=time.localtime(100000000)
ret1=time.mktime(ret)
print(ret1) #100000000.0
print(type(ret1)) #<class 'float'> #结构化时间--->时间字符串
ret=time.localtime(100000000)
ret2=time.strftime("%Y-%m-%d %H:%M:%S",ret)
print(ret2) #1973-03-03 17:46:40 #时间字符串--->结构化时间
ret3=time.strptime(ret2,"%Y-%m-%d %H:%M:%S")
print(ret3) #时间差
time1=time.mktime(time.strptime('2018-10-31 23:11:11','%Y-%m-%d %H:%M:%S'))
time2=time.mktime(time.strptime('2018-11-25 13:13:43','%Y-%m-%d %H:%M:%S')) #先将时间字符串转化为时间戳
ret=time2-time1
struct_t=time.localtime(ret) #再将时间戳转化为结构化时间
print("相差了%d年%d月%s天%d小时%d分%d秒"%(struct_t.tm_year-1970,struct_t.tm_mon-1,struct_t.tm_mday-1,struct_t.tm_hour,struct_t.tm_min,stru
三、random模块
import random #随机小数
print(random.random()) # 大于0且小于1之间的小数
print(random.uniform(1,3)) #大于1小于3的小数 #随机整数
#print(random.randint()) #randint() missing 2 required positional arguments: 'a' and 'b'
print(random.randint(1,5))
print(random.randrange(1,10,2)) #大于等于1且小于10之间的奇数 #随机选择一个返回
a=random.choice([1,2,3,4,5,'a'])
# print(a) #随机选择多个返回,返回的个数为函数的第二个参数
b=random.sample([1,'',[4,5]],3)
print(b) #打乱列表顺序
item=[1,3,5,78,987]
random.shuffle(item)
print(item) #练习:生成随机验证码 import random
code=''
for i in range (6):
zimu = chr(random.randint(65, 90))
suzi = random.randint(0, 9)
add=random.choice([zimu,suzi])
code=''.join([code,str(add)]) print(code)
collections&time&random模块的更多相关文章
- 4-24日 collections模块 random模块 time模块 sys模块 os模块
1, collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.defaultdi ...
- day19:常用模块(collections,time,random,os,sys)
1,正则复习,re.S,这个在用的最多,re.M多行模式,这个主要改变^和$的行为,每一行都是新串开头,每个回车都是结尾.re.L 在Windows和linux里面对一些特殊字符有不一样的识别,re. ...
- 21 模块(collections,time,random,os,sys)
关于模块importfrom xxx import xxx2. Collections1. Counter 计数器2. 栈: 先进后出.队列:先进先出deque:双向队列3. defaultdict ...
- Python——collections模块、time模块、random模块、os模块、sys模块
1. collections模块 (1)namedtuple # (1)点的坐标 from collections import namedtuple Point = namedtuple('poin ...
- python学习之老男孩python全栈第九期_day019知识点总结——collections模块、时间模块、random模块、os模块、sys模块
一. collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:namedtuple.deque.Counte ...
- python常用模块collections os random sys
Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句. 模块让你能够有逻辑地组织你的 Python 代码段. 把相关的代码 ...
- python time模块 sys模块 collections模块 random模块 os模块 序列化 datetime模块
一 collections模块 collections模块在内置的数据类型,比如:int.str.list.dict等基础之上额外提供了几种数据类型. 参考博客 http://www.pythoner ...
- day13 函数模块之序列化 random 模块 os模块 sys模块 hashlib模块 collections模块
json import json dic = {'k1':'v1','k2':'v2','k3':'v3'} str_dic = json.dumps(dic) #序列化:将一个字典转换成一个字符串 ...
- collections、random、hashlib、configparser、logging模块
collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.defaultdict. ...
随机推荐
- day44-Celery异步分布式
celery异步分布式Celery是一个python开发的异步分布式任务调度模块.Celery本身并不提供消息服务,使用第三方服务,也就是borker来传递任务,目前支持rebbimq,redis, ...
- https://www.cnblogs.com/h2zZhou/p/5440271.html
https://www.cnblogs.com/h2zZhou/p/5440271.html
- DB2还原数据库备份
用命令还原数据库备份 1.建立一个新的数据库db2 create db 数据库名 on 路径 using codeset GBK territory zh_CN 2.将需要恢复的数据库恢复得到这个新的 ...
- 记录这段时间java编程的小知识点
记录这段时间java编程的小知识点 eclipse项目导入中文乱码 eclipse左侧目录结构变动 eclipse代码段左右移动 按tal键,是整体右移. 按shift table 同时按,是整体左 ...
- layui在open弹出层回显,解决动态select数据回显问题
//监听数据表格工具条 table.on('tool(contentList)', function(obj){ //注:tool是工具条事件名,test是table原始容器的属性 l ...
- SolrCloud7.4(Jetty容器)+mysql oracle 部署与应用
SolrCloud7.4(Jetty容器)搭建 1.Zookeeper搭建 版本:zookeeper-3.4.10.tar.gz 1.把zookeeper安装包上传到服务器 2.zookeeper解压 ...
- 浅谈java 之 Map
先来一张Map的类继承图 Map :Hashtable .HashMap .LinkedHashMap .TreeMap 的比较 1.Hashtable的方法实现了synchronized 是线程 ...
- ResNet网络再剖析
随着2018年秋季的到来,提前批和内推大军已经开始了,自己也成功得当了几次炮灰,不过在总结的过程中,越是了解到自己的不足,还是需要加油. 最近重新复习了resnet网络,又能发现一些新的理念,感觉很f ...
- 苹果IOS下text-shadow与box-shadow失效的解决办法
加入以下样式,可以解决苹果IOS下text-shadow与box-shadow失效的问题 -webkit-appearance: none
- SSM excel文件的导入导出
对于excel文件的导入导出,后台接收读取和建表封存都是固定死的,所以对于excel导入时,excel文件内容必须匹配后台相关对象,不然报错. excel文件导出,用<a><a/&g ...