一、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模块的更多相关文章

  1. 4-24日 collections模块 random模块 time模块 sys模块 os模块

    1, collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.defaultdi ...

  2. day19:常用模块(collections,time,random,os,sys)

    1,正则复习,re.S,这个在用的最多,re.M多行模式,这个主要改变^和$的行为,每一行都是新串开头,每个回车都是结尾.re.L 在Windows和linux里面对一些特殊字符有不一样的识别,re. ...

  3. 21 模块(collections,time,random,os,sys)

    关于模块importfrom xxx import xxx2. Collections1. Counter 计数器2. 栈: 先进后出.队列:先进先出deque:双向队列3. defaultdict ...

  4. Python——collections模块、time模块、random模块、os模块、sys模块

    1. collections模块 (1)namedtuple # (1)点的坐标 from collections import namedtuple Point = namedtuple('poin ...

  5. python学习之老男孩python全栈第九期_day019知识点总结——collections模块、时间模块、random模块、os模块、sys模块

    一. collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:namedtuple.deque.Counte ...

  6. python常用模块collections os random sys

    Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句. 模块让你能够有逻辑地组织你的 Python 代码段. 把相关的代码 ...

  7. python time模块 sys模块 collections模块 random模块 os模块 序列化 datetime模块

    一 collections模块 collections模块在内置的数据类型,比如:int.str.list.dict等基础之上额外提供了几种数据类型. 参考博客 http://www.pythoner ...

  8. day13 函数模块之序列化 random 模块 os模块 sys模块 hashlib模块 collections模块

    json import json dic = {'k1':'v1','k2':'v2','k3':'v3'} str_dic = json.dumps(dic) #序列化:将一个字典转换成一个字符串 ...

  9. collections、random、hashlib、configparser、logging模块

    collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.defaultdict. ...

随机推荐

  1. 【nowcoder】 4th T2 区间

    题目链接:https://www.nowcoder.com/acm/contest/175/B 当你为时间复杂度挠头的时候 别人已经33行拿满分了 #include<cstdio> #in ...

  2. srping的历史与哲学

    历史: 要谈Spring的历史,就要先谈J2EE.J2EE应用程序的广泛实现是在1999年和2000年开始的,它的出现带来了诸如事务管理之类的核心中间层概念的标准化,但是在实践中并没有获得绝对的成功, ...

  3. SSH框架分页

    DAO层 /** * 分页查询全部员工,获取总记录数 */ public int totalPage(String className); /** * 分页查看,查看首页 */ public List ...

  4. nextcloud大文件无法上传

    I think that if u got a small /tmp like i had u cant upload big file…My /tmp = 462M so i can upload ...

  5. VS2017提醒找不到MSVCR110D.dll

    我的电脑时win10我已解决,不能传文件,需要联系我

  6. 解决Eclipse中.properties文件中文乱码问题

    在.properties文件写注释时,发现中文乱码了,由于之前在idea中有见设置.properties文件的编码类型,便找了找乱码原因 在中文操作系统中,Eclipse中的Java类型文件的编码的默 ...

  7. linux IPtable防火墙 禁止和开放端口

    1.关闭所有的 INPUT FORWARD OUTPUT 只对某些端口开放.下面是命令实现: iptables -P INPUT DROPiptables -P FORWARD DROPiptable ...

  8. Java之for循环嵌套练习

    1.打印4层*** ***** ***** ***** ***** class forfor{ public static void main(String[] args){ for(int y=0; ...

  9. [NOIP2013D2]

    T1 Problem 洛谷 Solution 这是线性扫描题吧. 就从1 ~ n 循环,若比起面高,则 ans += h[i] - h[i - 1]. Code #include<cmath&g ...

  10. 浅谈redis的HyperLogLog与布隆过滤器

    首先,HyperLogLog与布隆过滤器都是针对大数据统计存储应用场景下的知名算法. HyperLogLog是在大数据的情况下关于数据基数的空间复杂度优化实现,布隆过滤器是在大数据情况下关于检索一个元 ...