广告
返回顶部
首页 > 资讯 > 后端开发 > Python >collections, time, o
  • 437
分享到

collections, time, o

collectionstime 2023-01-31 00:01:30 437人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

1,collections模块 统计字符串总字母的个数 1 s = 'adskknawefkiewuhfbajfdcLSANlff' 2 dic = {} 3 for c in s: 4 dic[c] = dic.get(c,

1,collections模块

  • 统计字符串总字母的个数
    1 s = 'adskknawefkiewuhfbajfdcLSANlff'
    2 dic = {}
    3 for c in s:
    4     dic[c] = dic.get(c,0) + 1
    5 print(dic)
    6 
    7 from collections import Counter
    8 c = Counter(s)
    9 print(c)
  • 栈和队列
    python中是能直接导入队列的模块
    队列:先进先出 first in first out (FIFO)
     1 import queue
     2 #创建队列
     3 q = queue.Queue()
     4 #放元素
     5 q.put("a")
     6 q.put("b")
     7 q.put("c")
     8 
     9 #拉元素
    10 print(q.get())
    11 print(q.get())
    12 print(q.get())
    13 #如果队列里面没有元素了,就阻塞,等待下一个元素的进入
    14 print(q.get())
    栈: 先进后出 first in last out
    1,入栈
    2,出栈
    属性:1,列表(容器)2,大小(size)3,栈顶指针(下一个装元素的位置)

     1 #栈
     2 #定义一个栈满了不能加数据的异常
     3 import traceback
     4 class FullError(Exception):
     5     pass
     6 #定义一个栈空了不能去数据的异常
     7 class EmptyError(Exception):
     8     pass
     9 class Zhan(object):
    10     def __init__(self,size):
    11         self.size = size
    12         self.index = 0
    13         self.lst = []
    14 
    15     def push(self,el):
    16         if self.index < self.size:
    17             self.lst.insert(self.index,el)
    18             self.index += 1
    19         else:
    20             raise FullError("栈满了")
    21 
    22     def pop(self):
    23         if self.index > 0:
    24             self.index -= 1
    25             self.lst.pop(self.index)
    26         else:
    27             raise EmptyError("栈空了")
    28 
    29 z = Zhan(5)
    30 try:
    31     z.push(1)
    32     z.push(2)
    33     z.push(3)
    34     z.push(4)
    35     z.push(5)
    36     #z.push(6)
    37 except FullError as e:
    38     print(e)
    39     val = traceback.fORMat_exc()
    40     print(val)
    41 print(z.lst)
    42 
    43 
    44 try:
    45     z.pop()
    46     z.pop()
    47     z.pop()
    48     z.pop()
    49     z.pop()
    50     z.pop()
    51 except EmptyError as e:
    52     print(e)



  • 双向队列

     1 from collections import deque
     2 #创建一个双向队列
     3 b = deque()
     4 
     5 #向对列中加入元素
     6 b.append("a")#默认向右加入
     7 b.append("b")#默认向右加入
     8 b.append("c")#默认向右加入
     9 #B : a,b,c
    10 b.appendleft("d")#向左加入
    11 #B :  d,a,b,c
    12 
    13 #向对列中拿出元素
    14 b.pop()#默认向右删除
    15 b.pop()#默认向右删除
    16 #B : d,a
    17 b.popleft()#向左删除
    18 #B : a

2,time

  时间分三种,时间戳,结构化时间,格式化时间,三者之间通过结构化的时间能相互转化

 

 1 import time
 2 print(time.time()) #得到一个时间戳,给机器看的#1560225767.5565157
 3 #时间戳是以1970-01-01 00:00:00为原点
 4 
 5 #格式化时间,
 6 print(time.strftime("%Y-%m-%d %H:%M:%S"))#2019-06-11 12:02:47
 7 
 8 #结构化时间
 9 print(time.localtime())#time.struct_time(tm_year=2019, tm_mon=6, tm_mday=11, tm_hour=12, tm_min=11, tm_sec=51, tm_wday=1, tm_yday=162, tm_isdst=0)
10 
11 #时间戳转化结构化时间
12 h = 18888822233
13 st = time.localtime(h)
14 print(st)#time.struct_time(tm_year=2568, tm_mon=7, tm_mday=24, tm_hour=23, tm_min=3, tm_sec=53, tm_wday=6, tm_yday=206, tm_isdst=0)
15 #结构化时间转化成格式化时间
16 ft = time.strftime("%Y-%m-%d %H:%M:%S", st)
17 print(ft)#2568-07-24 23:03:53
18 
19 #格式化时间转化结构化时间
20 s = "2019-07-24 23:03:53"
21 ht = time.strptime(s,"%Y-%m-%d %H:%M:%S")
22 print(ht)#time.struct_time(tm_year=2019, tm_mon=7, tm_mday=24, tm_hour=23, tm_min=3, tm_sec=53, tm_wday=2, tm_yday=205, tm_isdst=-1)
23 #结构化时间转换时间戳
24 c = time.mktime(ht)
25 print(c)#1563980633.0

 

  时间格式

  

%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 当前时区的名称
%% %号本身
View Code

 

3,os模块

  os模块是与操作系统交互的一个接口,运行操作系统的命令

  

 1 os.makedirs('dirname1/dirname2')    可生成多层递归目录
 2 os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
 3 os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
 4 os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
 5 os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
 6 os.remove()  删除一个文件
 7 os.rename("oldname","newname")  重命名文件/目录
 8 os.stat('path/filename')  获取文件/目录信息
 9  
10 os.system("bash command")  运行shell命令,直接显示
11 os.popen("bash command).read()  运行shell命令,获取执行结果
12 os.getcwd() 获取当前工作目录,即当前Python脚本工作的目录路径
13 os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
14  
15  
16 os.path
17 os.path.abspath(path) 返回path规范化的绝对路径
18 os.path.split(path) 将path分割成目录和文件名二元组返回
19 os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
20 os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
21 os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
22 os.path.isabs(path)  如果path是绝对路径,返回True
23 os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False
24 os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False
25 os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
26 os.path.getatime(path)  返回path所指向的文件或者目录的最后访问时间
27 os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间
28 os.path.getsize(path) 返回path的大小

 

 1 stat 结构:
 2  
 3 st_mode: inode 保护模式
 4 st_ino: inode 节点号。
 5 st_dev: inode 驻留的设备。
 6 st_nlink: inode 的链接数。
 7 st_uid: 所有者的用户ID。
 8 st_gid: 所有者的组ID。
 9 st_size: 普通文件以字节为单位的大小;包含等待某些特殊文件的数据。
10 st_atime: 上次访问的时间。
11 st_mtime: 最后一次修改的时间。
12 st_ctime: 由操作系统报告的"ctime"。<br>在某些系统上(如Unix)是最新的元数据更改的时间,在其它系统上(如windows)是创建时间(详细信息参见平台的文档)。
13 
14 
15 os.sep    输出操作系统特定的路径分隔符,win下为"\\",linux下为"/"
16 os.linesep    输出当前平台使用的行终止符,win下为"\r\n",Linux下为"\n"
17 os.pathsep    输出用于分割文件路径的字符串 win下为;,Linux下为:
18 os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'

 

4,sys模块

  

 1 sys.argv           命令行参数List,第一个元素是程序本身路径
 2 sys.exit(n)        退出程序,正常退出时exit(0),错误退出sys.exit(1)
 3 sys.version        获取Python解释程序的版本信息
 4 sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
 5 sys.platform       返回操作系统平台名称
 6   
 7 import sys
 8 try:
 9     sys.exit(1)
10 except SystemExit as e:
11     print(e)

 

5,random模块

random模块是用来产生随机数的

 1 print(random.random()) #  0-1小数  想办法完成[1,100]之间的随机整数
 2 print(random.uniform(1, 3)) # 1-3之间的小数
 3  
 4 print(random.randint(1, 36)) # [1,36]随机整数
 5 print(random.randrange(1, 5, 3)) # [1, 5) 步长是3
 6  
 7  
 8 print(random.choice(["马化腾", ["倚天屠龙记", "天龙八部", "射雕"], "张无忌", "周伯通", "刘伟"])) <br># 随机选一个
 9 print(random.sample(["刘伟", "大阳哥", "大猪蹄子", "胡辣汤"], 3))
10 print(random.sample(list(range(1,37)), 7))
11  
12  
13 lst = [1,2,3,4,5,5,6,7,8,9,]
14 random.shuffle(lst) # 随机打烂列表顺序
15 print(lst)

 

--结束END--

本文标题: collections, time, o

本文链接: https://www.lsjlt.com/news/182695.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • collections, time, o
    1,collections模块 统计字符串总字母的个数 1 s = 'adskknawefkiewuhfbajfdcLSANlff' 2 dic = {} 3 for c in s: 4 dic[c] = dic.get(c,...
    99+
    2023-01-31
    collections time
  • python3--模块collections,time,random,sys
    defaultdict(默认字典)有如下值集合[11,22,33,44,55,66,77,88,99,90......],将所有大于66的值保存至字典的第一个key中,小于66的值保存至第二个key的值中即:{'k1':大于...
    99+
    2023-01-30
    模块 collections sys
  • Collections -- Order
    普通dict(字典)在插入的时候并不记住元素的顺序,迭代器会根据散列表(哈希表)中存储的顺序来生成的。而OrderedDict则会记录元素的顺序,并且在迭代器输出时,会按现在记录的顺序进行遍历。 例: 创建有序字典:   import c...
    99+
    2023-01-30
    Collections Order
  • ORA-30079: cannot alter database timezone when database has TIMESTAMP WITH LOCAL TIME ZONE columns O
    文档解释 ORA-30079: cannot alter database timezone when database has TIMESTAMP WITH LOCAL TIME ZONE columns Cause: An attemp...
    99+
    2023-11-05
    报错 故障 database
  • collections模块
      collections模块在内置数据类型(dict、list、set、tuple)的基础上,还提供了几个额外的数据类型:ChainMap、Counter、deque、defaultdict、namedtuple和OrderedDict...
    99+
    2023-01-30
    模块 collections
  • ORA-27619: Smart I/O failed because of an internal error when determining the time zone file version
    文档解释 ORA-27619: Smart I/O failed because of an internal error when determining the time zone file version. Error code &#...
    99+
    2023-11-05
    报错 故障 error
  • 3 - collections 模块
    collections 数据类型主要是为了弥补 list /tuple / dict 的额外数据类型 ChainMap 代码: import collections ## 赋值,合并字典的作用 a = {'a':"A"} b = {"b...
    99+
    2023-01-31
    模块 collections
  • 集合模块collections
    collections是Python内建的一个集合模块,提供了许多有用的集合类。 namedtuple 我们知道tuple可以表示不变集合,例如,一个点的二维坐标就可以表示成: >>> p = (1, 2) 但是,看到...
    99+
    2023-01-31
    模块 collections
  • python模块之collections
    计数器 Counter 计数元素迭代器 elements() 计数对象拷贝 copy() 计数对象清空 clear() from collections import Counter #import collection...
    99+
    2023-01-30
    模块 python collections
  • 25 Python的collections模块
    概述         在上一节,我们介绍了Python的sqlite3模块,包括:sqlite3模块中一些常用的函数和类。在这一节,我们将介绍Python的collections模块。collections模块是Python中的内置模块,它...
    99+
    2023-10-19
    python collections模块
  • python3--模块configparser,logging,collections
    configparser模块该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)创建文件import configparserconfig = configpar...
    99+
    2023-01-30
    模块 configparser collections
  • 深入理解Collections API(转)
    一个 List l 可能被做如下排序: Collections.sort(l); 如果这个 list 由 String 元素所组成, 那么它将按词典排序法(按字母顺序)进行排序; 如果它是由 Date 元素所组成, 那么它将按年代顺序来排序...
    99+
    2023-06-03
  • Java - 集合工具类Collections
    文章目录 目录 文章目录 前言 二.collections提供的方法  三. 方法详解 1.addAll:将所有指定元素添加到指定 collection 中。 可变参数  添加方式 二.shuffle():随机打乱List集合中的元素  ...
    99+
    2023-09-02
    开发语言 java
  • python: time
    time():获取时间戳gmtime() :换算成UTC时区的时间------->换成元组的形式localtime():结果为UTC+8时区 例:获取各个属性import timex=time.localtime() #获取当前时间p...
    99+
    2023-01-31
    python time
  • ORACLE 时间与时区(Time and Time Zone)
    转:https://www.2cto.com/database/201110/107435.html 一) Oracle中的四种时间类型 Date Timestamp ...
    99+
    2022-10-18
  • 深入浅析Collections工具类
    深入浅析Collections工具类?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。Collections工具类提供了大量针对Collection/Map的操作,总体可分为四...
    99+
    2023-05-31
    collections 工具类 ct
  • 必须知道的collections模块
    先来看一下collections模块中的方法: __all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList', 'UserStrin...
    99+
    2023-01-31
    模块 collections
  • Python time strptime
    描述 Python time strptime() 函数根据指定的格式把一个时间字符串解析为时间元组。 语法 strptime()方法语法: time.strptime(string[, format]) 参数 string -- ...
    99+
    2023-01-30
    Python time strptime
  • time模块
        在Python中,用三种方式来表示时间,分别是时间戳、格式化时间字符串和结构化时间   获取时间戳:time.time() ====>如1506388236.216345   获取格式化时间字符串(str f time)...
    99+
    2023-01-30
    模块 time
  • Python中time
    def get_time(): time_array = time.localtime() time_array = time.mktime(time_array) return time.strftime("%Y ...
    99+
    2023-01-31
    Python time
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作