Python——collections模块、time模块、random模块、os模块、sys模块
1. collections模块
(1)namedtuple
# (1)点的坐标
from collections import namedtuple
Point = namedtuple('point',['x','y']) # 前两行可以用下面两行代替
# import collections
# Point = collections.namedtuple('point',['x','y'])
p = Point(1,2)
print(p.x) #
print(p.y) #
print(p) #point(x=1, y=2)
扑克牌的花色和数字
from collections import namedtuple
Card = namedtuple('card',['suits','number'])
c1 = Card('红桃',2)
print(c1.suits) #红桃
print(c1.number) #
print(c1) #card(suits='红桃', number=2)
(2)queue 队列——FIFO 先进先出
import queue q = queue.Queue()
q.put(10)
q.put(5)
q.put(8)
print(q.qsize()) #
print(q) #<queue.Queue object at 0x00000144985010B8>
print(q.get()) #
print(q.get()) #
print(q.get()) #
print(q.get()) #阻塞:取完值之后继续取,不会报错
(3)deque——双端队列
from collections import deque
dq = deque([5,6])
dq.appendleft('a') #从前面放数据 ['a',5,6]
dq.append('b') #从后面放数据 ['a',5,6,'b']
dq.insert(0,3) # [3,'a',5,6,'b']
print(dq) #deque([3, 'a', 5, 6, 'b'])
print(dq.popleft()) #从前面取数据:3
print(dq.popleft()) #从前面取数据:a
print(dq.pop()) #从后面取数据:b
print(dq.pop()) #从后面取数据:6
print(dq) #deque([5])
(4)OrderedDict 有序字典
字典取值快,但是存储时比列表占内存多
from collections import OrderedDict
od = dict([('a',1),('b',2),('c',3)])
print(od) #有序:{'a': 1, 'b': 2, 'c': 3}
print(od['a']) #
for k in od:
print(k) # a b c
(5)defaultdict——默认字典
key不存在时,返回一个默认值
举例:将大于66的数放在k1,小于66的数放在k2
from collections import defaultdict
values = [11,22,33,44,55,66,77,88,99,100]
my_dict = defaultdict(list) #默认list
for value in values:
if value>66:
my_dict['k1'].append(value)
else:
my_dict['k2'].append(value)
print(my_dict['k1']) #[77, 88, 99, 100]
print(my_dict['k2']) #[11, 22, 33, 44, 55, 66]
defaultdict的用法
from collections import defaultdict
d = defaultdict(list)
print(d['k']) #[] from collections import defaultdict
d1 = defaultdict(dict)
print(d1['k']) #{} from collections import defaultdict
dd = defaultdict(lambda:'默认值')
dd['key1'] = 'abc'
print(dd['key1']) #key1存在,返回:abc
print(dd['key2']) #key2不存在,返回:默认值(可以随意设置)
(6)Counter——跟踪值出现的次数
from collections import Counter
c = Counter('abacadfdcbcdf')
print(c) #Counter({'a': 3, 'c': 3, 'd': 3, 'b': 2, 'f': 2})
2. time模块
(1)时间戳时间(timestamp)——float时间:给计算机看的
(2)格式化时间(Format String)——字符串:给人看的
#格式化时间:时间字符串strftime print(time.strftime('%Y-%m-%d %a %H:%M:%S' )) # 2018-10-08 Mon 15:04:01 Year month day week Hour Minute Seconds
print(time.strftime('%Y/%m/%d %H:%M:%S' )) # 2018/10/08 15:05:23 Year month day Hour Minute Seconds
print(time.strftime('%m-%d %H:%M:%S' )) # 10-08 15:04:01 month day Hour Minute Seconds
print(time.strftime('%H:%M:%S' )) # 15:04:01 Hour Minute Seconds
print(time.strftime('%H:%M' )) # 15:04 Hour Minute
(3)结构化时间(struct_time)——元祖:计算用的
#结构化时间 #localtime
struct_time = time.localtime()
print(struct_time) #time.struct_time(tm_year=2018, tm_mon=10, tm_mday=8, tm_hour=15, tm_min=7, tm_sec=53, tm_wday=0, tm_yday=281, tm_isdst=0)
print(struct_time.tm_year) # #gmtime
struct_time1 = time.gmtime()
print(struct_time1) #time.struct_time(tm_year=2018, tm_mon=10, tm_mday=8, tm_hour=15, tm_min=7, tm_sec=53, tm_wday=0, tm_yday=281, tm_isdst=0)
print(struct_time1.tm_year) #
(4)三者的相互转换
(5)相互转换代码
t = time.time()
print(t) #1538982828.2859974
print(time.localtime(t)) #time.struct_time(tm_year=2018, tm_mon=10, tm_mday=8, tm_hour=15, tm_min=13, tm_sec=3, tm_wday=0, tm_yday=281, tm_isdst=0)
print(time.gmtime(t)) #time.struct_time(tm_year=2018, tm_mon=10, tm_mday=8, tm_hour=7, tm_min=13, tm_sec=3, tm_wday=0, tm_yday=281, tm_isdst=0)
print(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) print(time.mktime(time.localtime())) #1538982958.0 t = time.strptime('2000-12.31','%Y-%m.%d')
print(t) #time.struct_time(tm_year=2000, tm_mon=12, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=366, tm_isdst=-1)
print(time.strftime('%m/%d/%y %H:%M:%S',time.localtime(3000000000))) #01/24/65 13:20:00 print(time.asctime()) # Mon Oct 8 15:21:02 2018
print(time.asctime(time.localtime())) # Mon Oct 8 15:21:02 2018
print(time.asctime(time.localtime(2000000000))) # Wed May 18 11:33:20 2033
print(time.ctime()) # Mon Oct 8 15:21:02 2018
print(time.ctime(2000000000)) # Wed May 18 11:33:20 2033
3. random模块
(1)随机小数
import random print(random.random()) # (0,1)之间的任意一个小数
print(random.uniform(1,3)) # (1,3)之间的任意一个小数
(2)随机整数
import random print(random.randint(1,5)) # [1,5]之间的任意一个整数
print(random.randrange(1,5)) # [1,4]之间的任意一个整数
print(random.randrange(1,10,2)) # [1,9]之间的任意一个整数奇数
(3)选择一个返回
import random print(random.choice([1,'',[4,5]])) # 随机选择一个返回:列表任意一个元素
(4)选择多个返回
import random print(random.sample([1,'',[4,5],5,4,9],3)) # 随机选择多个返回:返回个数是函数的第二个参数
(5)打乱列表序列
import random item = [1,3,5,7,9]
print(item) # [1, 3, 5, 7, 9]
random.shuffle(item)
print(item) # [5, 9, 3, 7, 1]
(6)验证码的生成
详见:笔试面试题 https://www.cnblogs.com/xc-718/p/9632731.html
4. sys模块
import sys sys.exit() # 退出程序:exit(1) 错误退出,exit(0) 正常退出
print(sys.platform) # win32【不准】
# 获取Python解释程序的版本信息
print(sys.version) # 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] # 返回模块的搜索路径
print(sys.path) # 所有路径
print(sys.path.clear()) # 清空之后,import sys 会报错
sys.argv
import sys print(sys.argv) # ['E:/Python/day19/06 sys.py'] ret = sys.argv
name = ret[1]
pwd = ret[2]
if name == 'xc' and pwd == '':
print('登陆成功')
else:
print('错误的用户名或密码')
sys.exit()
print('你可以使用本系统了')
5.os模块
(1)os.getcwd()
import os print(os.getcwd()) #获取当前工作目录: E:\Python\day19
os.chdir(r'E:\Python') #改变当前脚本的工作目录,一般不会用到
print(os.getcwd()) #获取当前工作目录: E:\Python
os.chdir(r'E:\Python\day19') #改变回原本的工作目录
print(os.getcwd()) #获取当前工作目录: E:\Python\day19
import sys print(sys.argv) # ['E:/Python/day19/06 sys.py'] ret = sys.argv
name = ret[1]
pwd = ret[2]
if name == 'xc' and pwd == '':
print('登陆成功')
else:
print('错误的用户名或密码')
sys.exit()
print('你可以使用本系统了')
(2)文件和目录操作
import os print(os.getcwd()) #E:\Python\day19
os.chdir('..') #改变目录到当前目录的父目录
print(os.getcwd()) #E:\Python print(os.curdir) # . 当前目录
print(os.pardir) # .. 当前目录的父目录,也就是上一层目录 os.makedirs('dir1/dir2') #创建多层目录
os.removedirs('dir1/dir2') #递归删除,一直删到上层目录不为空为止
os.mkdir('dir1') #创建单级目录
os.rmdir('dir1') #删除单极空目录,不为空不删除 print(os.listdir(r'E:\Python\day19')) #列出指定目录下所有的文件和子目录,包含隐藏文件,并以列表方式打印 os.rename('06.sys.py','06 sys.py') # 重命名文件
os.remove('E:/Python/day19/07 delete') # 删除一个文件 print(os.stat('E:/Python/day19/06 作业.py')) # 获取文件/目录信息
(3)代码跨平台
import os # python 代码跨平台
print(os.sep)
# 输出操作系统特定的路径分隔符
# windows \ E:\Python\day19
# linux / E:/Python/day19
print(os.pathsep)
# 输出用于分割文件路径的字符串
# windows ; E:\Python\day19;E:\Python\day19;E:\Python\day19
# linux : E:\Python\day19:E:\Python\day19:E:\Python\day19
print(os.name)
# 输出字符串指示当前平台
# windows nt
# linux posix
(4)与路经有关
import os # 与路径有关的
print(os.path) #绝对路径 <module 'ntpath' from 'D:\\download\\Python\\lib\\ntpath.py'>
# 返回path规范化的绝对路径
print(os.path.abspath(os.getcwd())) #E:\Python\day19 print(os.getcwd()) # 获取当前路径 E:\Python\day19
# 用split将路径分割成:(目录,文件名)
print(os.path.split(os.getcwd())) #('E:\\Python', 'day19') # 返回path的目录
print(os.path.split(os.getcwd())) #('E:\\Python', 'day19')
print(os.path.dirname(os.getcwd())) # E:\Python
print(os.path.basename(os.getcwd())) # day19 print(os.path.exists()) # path存在,返回True;不存在,返回False
print(os.path.isabs()) # path是绝对路径,返回True
print(os.path.isfile()) # path是一个存在的文件,返回True
print(os.path.isdir()) # path 是一个存在的目录,返回True
print(os.path.join('c:','user','local')) # c:user\local 多个路径组合后返回,第一个绝对路径之前的参数被忽略
print(os.path.getatime()) # 返回path所指向的文件/目录的最后访问时间
print(os.path.getmtime()) # 返回path所指向的文件/目录的最后修改时间 # 返回path的大小
print(os.path.getsize(os.getcwd())) # 4096【文件夹最大这么大】
print(os.path.getsize(os.path.join(os.getcwd(),'03 time.py'))) # 2546【文件大小】
(5)其他
import os os.system('dir') # 运行shell命令,直接显示,无返回值不能直接操作
print(os.popen('dir').read()) # 运行shell命令,获取执行结果,有返回值 # 获取系统的环境变量
print(os.environ)
Python——collections模块、time模块、random模块、os模块、sys模块的更多相关文章
- collections,time,random,os, sys 模块的使用
主要内容:1. 模块的简单认识2. collections模块3. time时间模块4. random模块5. os模块6. sys模块 一. 模块的简单认识什么是模块. 模块就是我们把装有特定功能的 ...
- python time、datetime、random、os、sys模块
一.模块1.定义模块:用来从逻辑上组织Python代码(变量,函数,类,逻辑:实现一个功能),本质就是.py结尾的python文件(文件名:test.py,对应的模块名:test)包:用来从逻辑上组织 ...
- python常用模块---collections、time、random、os、sys、序列号模块
collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.defaultdict. ...
- Python进阶-XI 常用模块之一:collections、time、random、os、sys
简要介绍一下各种集合: 列表.元组.字典.集合(含frozenset).字符串.堆栈(如手枪弹夹:先进后出).队列(如马克沁机枪的弹夹:先进先出) 1.collections 1)queue 队列介绍 ...
- python之random 、os 、sys 模块
一.random模块 import random print(random.random())#(0,1)----float 大于0且小于1之间的小数 print(random.randint(1,3 ...
- Python (time、datetime、random、os、sys、shutil)模块的使用
######################################################### 模块time ################################### ...
- Python os与sys模块解析
os与sys模块的官方解释如下: os: This module provides a portable way of using operating system dependent functio ...
- Python中os与sys模块的区别
os与sys模块的官方解释如下: os: This module provides a portable way of using operating system dependent functio ...
- python os和sys模块使用
python os和sys模块使用 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目录:相 ...
- Python 的 os 与 sys 模块
os与sys模块的官方解释如下: os: This module provides a portable way of using operating system dependent functio ...
随机推荐
- Win10取消密码
- System.Web.Caching
System.Web.Caching简单封装类: using System; using System.Collections.Generic; using System.Web.Caching; u ...
- iOS 9 通用链接(Universal Links)
什么是Universal Links? 在iOS9之前,对于从各种从浏览器.Safari中唤醒APP的需求,我们通常只能使用scheme.但是这种方式需要提前判断系统中是否安装了能够响应此scheme ...
- DevExpress WPF入门指南:如何自动或手动添加DXSplashScreen控件
<DevExpress v17.2 版本更新公开课>点击报名 DevExpress WPF 的 DXSplashScreen 控件在应用加载的时候显示一个启动界面.添加DXSplashSc ...
- C++内存管理-重载内存管理函数
记录学习的点点滴滴,参考侯捷<<C++内存管理>> 我们先重载一下C++的几个内存管理函数 operator new, operator new[], operator del ...
- 2018-2019-2 网络对抗技术 20165202 Exp2 后门原理与实践
博客目录 一.基础问题回答 二.实验准备:后门软件 1.Windows获得Linux Shell 2.Linux获得Windows Shell 3.使用nc传输数据 4.使用ncat实现文件传输 三. ...
- anu - reactIE
import { options } from "./util"; import { Children } from "./Children"; import ...
- pygame精灵类实现房子爆炸效果
# coding=utf8 import random import pygame from pygame.locals import * from cStringIO import StringIO ...
- P2S、P2P、P2SP之对比
P2S.P2P.P2SP之对比 一.下载原理分析 1.服务端下载技术(P2S):P2S下载方式分为HTTP与FTP两种类型,它们分别是Hyper Text Transportation Protoco ...
- linux 优化git操作速度
修改 ssh配置:useDNS:no