python-day21(模块初级)

一. 关于模块

  import  xxx

  from xxx import xxx

二. Collections

  1. Counter 计数器

 1 from collections import Counter
 2 
 3 # s = "I am sylar, I have a dream, freedom...."
 4 # dic = {}
 5 # for el in s:
 6 #     dic[el] = dic.setdefault(el, 0) + 1
 7 # print(dic)
 8 #
 9 # qq = Counter(s)
10 #
11 # print("__iter__" in dir(qq))
12 # for item in qq:
13 #     print(item, qq[item])
14 
15 # lst = ["五花马", "千金裘", "不会", "不会", "不会"]
16 # c = Counter(lst)
17 # print(c['五花马'])
18 
19 # dic = {"a":"b", "c":"d"}
20 # print(dic.keys())
View Code

  2. 栈: 先进先出

 1 # class StackFullError(Exception):
 2 #     pass
 3 # class StackEmptyError(Exception):
 4 #     pass
 5 #
 6 # class Stack:
 7 #     def __init__(self, size):
 8 #         self.index = 0 #  栈顶指针
 9 #         self.lst = []
10 #         self.size = size
11 #
12 #     # 给栈添加元素
13 #     def push(self, item):
14 #         if self.index == self.size:
15 #             # 栈已经满了. 不能再装东西了
16 #             raise StackFullError('the stack is full')
17 #         self.lst.insert(self.index, item) # 对于空列表. 需要insert插入内容
18 #         # self.lst[self.index] = item # 把元素放到栈里
19 #         self.index += 1     # 栈顶指针向上移动
20 #
21 #     # 从栈中获取数据
22 #     def pop(self):
23 #         if self.index == 0:
24 #             raise StackEmptyError("the stack is empty")
25 #         self.index -=1 # 指针向下移动
26 #         item = self.lst.pop(self.index) # 获取元素. 删除.
27 #         return item
28 # s = Stack(5)
29 # s.push("馒头1号")
30 # s.push("馒头2号")
31 # s.push("馒头3号")
32 # s.push("馒头4号")
33 # s.push("馒头5号")
34 #
35 # print(s.pop())
36 # print(s.pop())
37 # print(s.pop())
38 # print(s.pop())
39 # print(s.pop())
View Code

    队列: 先进先出

    deque: 双向队列

 1 # 队列
 2 # import queue
 3 # #
 4 # q = queue.Queue() # 创建队列
 5 # q.put("李嘉诚")
 6 # q.put("陈冠希")
 7 # q.put("周润发")
 8 # q.put("吴彦祖")
 9 #
10 # print(q.get())
11 # print(q.get())
12 # print(q.get())
13 # print(q.get())
14 # # print(q.get()) # 队列中如果没有元素了. 继续获取的话. 会阻塞
15 # print("拿完了")
16 
17 # from collections import deque
18 #
19 # q = deque() # 创建一个双向队列
20 # q.append("高圆圆")
21 # q.append("江疏影")
22 # q.appendleft("赵又廷")
23 # q.appendleft("刘大哥")
24 # #  刘大哥 赵又廷 高圆圆 江疏影
25 # print(q.pop()) # 从右边获取数据
26 # print(q.pop())
27 # print(q.popleft()) # 从左边获取数据
28 # print(q.popleft())
29 # print(q.pop())
View Code

  3. defaultdict 默认值字典

 1 from collections import defaultdict
 2 
 3 # d = defaultdict(list) # {} # 参数位置给的内容必须是可调用的
 4 # d["周杰伦"] = "昆凌"
 5 # print(d["周杰伦"]) # 从字典中获取数据的时候. 如果这个key不存在. 去执行可执行的内容, 拿到的是一个空列表
 6 
 7 # lst= [11,22,33,44,55,66,77,88,99]
 8 # d = defaultdict(list)
 9 # for el in lst:
10 #     if el < 66:
11 #         d["key1"].append(el) # key1默认是不存在的. 但是可以拿key1. 一个空列表.
12 #     else:
13 #         d["key2"].append(el)
14 # print(d)
15 
16 
17 
18 # lst = [11,22,33,44,55,66,77,88,99]
19 # dic = {}
20 # for i in lst:
21 #     if i<=66:
22 #         dic.setdefault('key1',[]).append(i)
23 #     else:
24 #         dic.setdefault('key2',[]).append(i)
View Code

  4. namedtuple 命名元祖. struc_time 结构化时间就是命名元祖

 1 # from collections import namedtuple
 2 #
 3 # point = namedtuple("Point", ["x", "y", 'z']) # 这个就相当于写了一个类
 4 # # class point:
 5 # #     def __init__(self, x, y):
 6 # #         self.x = x
 7 # #         self.y = y
 8 #
 9 # p = point(5, 18, 88)
10 # print(p.x)
11 # print(p.y)
12 # # p.x = 19 # 终归是一个元组
13 # print(p)
View Code

  5. OreddereDict 有序字典. 按照我们储存的顺序保存. 和3.6以后 的字典一样的

 1 # dic = {'a':'娃哈哈', 'b':'薯条', 'c':'胡辣汤'}
 2 # print(dic) # 最底层一定是无序的. 最底层是hash
 3 #
 4 # from collections import OrderedDict
 5 # # 按照我们存储的顺序保存数据
 6 # od = OrderedDict({ 'b':'薯条','a':'娃哈哈', 'c':'胡辣汤'})
 7 # print(od)
 8 
 9 # dic = {}
10 # print(dic["周润发"]) # 报错
11 # print(dic.get("周润发", "英雄本色")) # None
View Code

三. time时间模块

  1. 获取系统时间 time.time() 时间戳

  2. 格式化时间 strftime()  时间格式: %Y-%m-%d    %H:%M:%S

  3. 结构化时间 time.gmtime()  time.localtime()

  strptime() 把格式化时间转化成结构化时间

  mktime() 把结构化时间转化成时间戳

import time
# print(time.time()) #时间戳
# print(time.strftime('%Y-%m-%d %H:%M:%S')) # 格式化时间
# print(time.gmtime())#结构化时间  格林尼治时间
# print(time.localtime())#结构化时间
# print(time.strptime('2018-01-01 00:01:00','%Y-%m-%d %H:%M:%S'))#格式化时间转化成结构化时间
# print(time.mktime(time.localtime()))#结构化时间转换成时间戳

  时间差的计算

 1 # 时间差  1小时30分
 2 # begin = "2018-11-14 16:30:00"
 3 # end = "2018-11-14 18:00:00"
 4 # # 用时间戳计算出时间差(秒)
 5 # begin_struct_time = time.strptime(begin, "%Y-%m-%d %H:%M:%S")
 6 # end_stract_time = time.strptime(end, "%Y-%m-%d %H:%M:%S")
 7 #
 8 # begin_second = time.mktime(begin_struct_time)
 9 # end_second = time.mktime(end_stract_time)
10 #
11 # # 秒级的时间差   180000
12 # diff_time_sec = abs(begin_second - end_second)
13 #
14 # # 转换成分钟
15 # diff_min = int(diff_time_sec//60)
16 # print(diff_min)
17 #
18 # diff_hour = diff_min//60  # 1
19 # diff_min_1 = diff_min % 60 # 30
20 #
21 # print("时间差是 %s小时%s分钟" % (diff_hour, diff_min_1))
22 
23 
24 
25 
26 
27 # begin = "2019-11-14 16:30:00"
28 # end = "2018-11-14 18:00:00"
29 # # 用时间戳计算出时间差(秒)
30 # begin_struct_time = time.strptime(begin, "%Y-%m-%d %H:%M:%S")
31 # end_stract_time = time.strptime(end, "%Y-%m-%d %H:%M:%S")
32 #
33 # begin_second = time.mktime(begin_struct_time)
34 # end_second = time.mktime(end_stract_time)
35 #
36 # # 秒级的时间差  180000
37 # diff_time_sec = abs(begin_second - end_second)
38 #
39 # # 转化成结构化时间
40 # t = time.gmtime(diff_time_sec) # 最好用格林尼治时间。 否则有时差
41 # print(t)
42 #
43 # print("时间差是%s年%s月 %s天 %s小时%s分钟" % (t.tm_year-1970, t.tm_mon-1, t.tm_mday-1,t.tm_hour, t.tm_min ))
View Code

四. os和sys

  os.spe 文件路劲分隔符

  sys.path  python查找模块的路径

 1 一、sys
 2 用于提供对Python解释器相关的操作:
 3 
 4 sys.argv           命令行参数List,第一个元素是程序本身路径
 5 sys.exit(n)        退出程序,正常退出时exit(0)
 6 sys.version        获取Python解释程序的版本信息
 7 sys.maxint         最大的Int值
 8 sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
 9 sys.platform       返回操作系统平台名称
10 sys.stdin          输入相关
11 sys.stdout         输出相关
12 sys.stderror       错误相关
13 
14 复制代码
15 import sys
16 import time
17 
18 
19 def view_bar(num, total):
20     rate = float(num) / float(total)
21     rate_num = int(rate * 100)
22     r = '
%d%%' % (rate_num, )
23     sys.stdout.write(r)
24     sys.stdout.flush()
25 
26 
27 if __name__ == '__main__':
28     for i in range(0, 100):
29         time.sleep(0.1)
30         view_bar(i, 100)
31 复制代码
32 二、os
33 用于提供系统级别的操作:
34 
35 os.getcwd()                 获取当前工作目录,即当前python脚本工作的目录路径
36 os.chdir("dirname")         改变当前脚本工作目录;相当于shell下cd
37 os.curdir                   返回当前目录: ('.')
38 os.pardir                   获取当前目录的父目录字符串名:('..')
39 os.makedirs('dir1/dir2')    可生成多层递归目录
40 os.removedirs('dirname1')   若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
41 os.mkdir('dirname')         生成单级目录;相当于shell中mkdir dirname
42 os.rmdir('dirname')         删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
43 os.listdir('dirname')       列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
44 os.remove()                 删除一个文件
45 os.rename("oldname","new")  重命名文件/目录
46 os.stat('path/filename')    获取文件/目录信息
47 os.sep                      操作系统特定的路径分隔符,win下为"\",Linux下为"/"
48 os.linesep                  当前平台使用的行终止符,win下为"	
",Linux下为"
"
49 os.pathsep                  用于分割文件路径的字符串
50 os.name                     字符串指示当前使用平台。win->'nt'; Linux->'posix'
51 os.system("bash command")   运行shell命令,直接显示
52 os.environ                  获取系统环境变量
53 os.path.abspath(path)       返回path规范化的绝对路径
54 os.path.split(path)         将path分割成目录和文件名二元组返回
55 os.path.dirname(path)       返回path的目录。其实就是os.path.split(path)的第一个元素
56 os.path.basename(path)      返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素
57 os.path.exists(path)        如果path存在,返回True;如果path不存在,返回False
58 os.path.isabs(path)         如果path是绝对路径,返回True
59 os.path.isfile(path)        如果path是一个存在的文件,返回True。否则返回False
60 os.path.isdir(path)         如果path是一个存在的目录,则返回True。否则返回False
61 os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
62 os.path.getatime(path)      返回path所指向的文件或者目录的最后存取时间
63 os.path.getmtime(path)      返回path所指向的文件或者目录的最后修改时间
View Code

五. rando(随机数)

 1 import random
 2 
 3 # print(random.randint(1,2))  # [start, end]
 4 # print(random.random()) # (0,1)之间的小数
 5 # print(random.uniform(3,10)) # (3, 10 )的随机小数
 6 
 7 # n = random.randrange(1, 10, 3) # [1, 10) 从奇数中获取到随机数
 8 # while n != 10:
 9 #     n = random.randrange(1, 10, 3)
10 
11 # for i in range(1, 10, 3):
12 #     print(i)
13 
14 print(random.choice([1, '周杰伦', ["盖伦", "胡辣汤"]])) #
15 print(random.sample([1, '23', [4, 5]], 2)) # 列表元素任意2个组合
16 
17 lst = ["周杰伦", "昆凌", "马化腾", "马丽", "沈腾", "秋雅"]
18 random.shuffle(lst)
19 print(lst)
View Code
原文地址:https://www.cnblogs.com/Thui/p/9959737.html