python学习第二十一天

1.关于模块。
import
from xxx import xxx
2.Collections

1. Counter 计数器
2. 栈: 先进后出.
队列:先进先出
deque:双向队列
3. defaultdict 默认值字典
4. namedtuple 命名元祖. struct_time 结构化时间就是命名元祖
5. OrederedDict 有序字典。 按照我们存储的顺序保存. 和3.6以后的字典一样的

# import collections # 方法二的引入模块
from collections import Counter

s = "I am Euan, I have a dream, freedom"

# 方法一
dic = {}
for el in s:
dic[el] = dic.setdefault(el,0) + 1
print(dic)

# 方法二
# q = collections.Counter(s)
# print(q)

# 方法三
q = Counter(s)

print("__iter__" in dir(q))
for item in q:
print(item,":",q[item])


# 栈 : 特点:先进后出
# 队列 : 特点:先进先出
# python中提供了队列,没有栈,

# 栈
# 自定义异常
class StackFullError(Exception): # 栈已满
pass
class StackEmptyError(Exception): # 栈已空
pass

class Stack:
def __init__(self, size):
'''

:param size: 栈的大小
'''
self.index = 0
self.lst = []
self.size = size

# 给栈添加元素
def push(self,item):
'''

:param item: 添加的元素
:return:
'''
if self.index == self.size:
# 栈已经满了不能添加内容,抛出一个异常
raise StackFullError('The stack is full')
self.lst.insert(self.index,item) # 对于一个空列表,需要insert插入内容
# self.lst.insert(self.index,item) 把元素放到栈里
self.index += 1 # 指针向上移动


# 从栈中获取数据
def pop(self):
'''

:return: 返回删除的元素(从栈中拿出的元素)
'''
if self.index == 0:
raise StackEmptyError('The stack is empty')
self.index -= 1 # 指针向下移动
item = self.lst.pop(self.index) # 获取元素,删除
return item

s = Stack(3)
s.push('1')
s.push('2')
s.push('3')
print(s.pop())
print(s.pop())
print(s.pop())

# 队列
# 队列中没有元素了,继续获取的话,会阻塞
import queue
q = queue.Queue() # 创建队列
q.put('Euan')
q.put('Xu')
q.put('Wade')
print(q)
print(q.get())
print(q.get())
print(q.get())

# 双向列表

from collections import deque
q = deque() # 创建双向列表
q.append('Euan') # 从右边添加数据
q.append('Kobe')
q.append('Wade')
q.appendleft('威斯布鲁克') # 从左边添加数据
q.appendleft('阿托姆昆伯')
q.appendleft('哈登')
print(q.pop()) # 从右边拿取数据
print(q.pop())
print(q.pop())
print(q.pop())
print(q.popleft()) # 从左边拿取数据
print(q.popleft())


# 命名元组
from collections import namedtuple
point = namedtuple("point",['x','y','z']) # 相当于写了一个类
# class Point:
# def __init__(self, x, y, z):
# self.x = x
# self.x = y
# self.x = z
p = point(7,16,25)
print(p)
print(p.x)

from collections import defaultdict

lst = [11,66,55,33,44,99,77,22,88,]

d = defaultdict(list)
for el in lst:
if el < 66 :
d["key1"].append(el)
else:
d["key2"].append(el)
print(d)



3.time时间模块

1. 获取系统时间 time.time() 时间戳
2. 格式化时间 strftime() 时间格式: %Y-%m-%d %H:%M:%S %Y-%m-%d
3. 结构化时间 time.gmtime() time.localtime()
strptime() 把格式化时间转化成结构化时间
mktime() 把结构化时间转化成时间戳


import time

# 获取当前时间系统,时间戳
print(time.time())
# 1542167259.4904895,给机器看的.
# 以1970-01-01 00:00:00为基准.
# 数据库存储的是这个时间.

# 格式化时间 2018-11-14 11:11:11
# 以下格式使用频率特别高
s = time.strftime("%Y-%m-%d %H:%M:%S") # string format time
print(s) # 打印当前时间

# 计时器
while 1:
s = time.strftime("%Y-%m-%d %H:%M:%S")
print(s)
time.sleep(1)


# 结构化时间
print(time.localtime())
t = time.localtime()
print(t.tm_yday)
print(t.tm_year)
print(t.tm_mon)


# # (从时间戳 ——> 格式化时间),(格式化时间 ——> 从时间戳),两者再转换时都必须先转换为结构化时间
# 从时间戳 ——> 格式化时间
# 数据库中存储的 时间戳:1542168201.0
t = time.localtime(1542168201.0) # localtime() : 当地时区 ; gmtime() : 格林尼治时间
print(t) # t 此时为 结构化时间
# 结构化时间 转换为 格式化时间
str_time = time.strftime("%Y-%m-%d %H:%M:%S", t)
print(str_time)

# 格式化时间 ——> 从时间戳
s = "2018-11-14 12:03:21"
t = time.strptime(s,"%Y-%m-%d %H:%M:%S") # ("%Y-%m-%d %H:%M:%S")这个格式必须和给出的时间格式一致
print(t) # t 此时为结构化时间
# 结构化时间长这样 : time.struct_time(tm_year=2018, tm_mon=11, tm_mday=14, tm_hour=12, tm_min=3, tm_sec=21, tm_wday=2, tm_yday=318, tm_isdst=-1)
# 结构化时间 转换为 时间戳
ss = time.mktime(t)
print(ss)


# 时间差
import time
# # 第一种方法
begin = "2018-11-14 16:30:00"
end = "2018-11-14 18:00:50"

begin_struct_time =time.strptime(begin, "%Y-%m-%d %H:%M:%S")
end_struct_time =time.strptime(end, "%Y-%m-%d %H:%M:%S")

begin_second = time.mktime(begin_struct_time)
end_second = time.mktime(end_struct_time)

diff_time = abs((begin_second - end_second))
min = int(diff_time//60)

diff_s = int(diff_time%60) # 最终秒的结果
diff_hour = (min//60) # 最终分钟的结果
diff_min = (min%60) # 最终小时的结果
print("时间差是 %s小时%s分钟%s秒钟" % (diff_hour, diff_min,diff_s))

# # 第二种方法
begin = "2018-11-14 16:30:00"
end = "2018-11-14 18:00:50"

begin_struct_time =time.strptime(begin, "%Y-%m-%d %H:%M:%S")
end_struct_time =time.strptime(end, "%Y-%m-%d %H:%M:%S")

begin_second = time.mktime(begin_struct_time)
end_second = time.mktime(end_struct_time)
diff_time_sec = abs((begin_second - end_second))

# # 以下为与方法一的不同点
# 转化成结构化时间
t = time.gmtime(diff_time_sec) # 最好用格林尼治时间。 否则有时差
print('时间差是%s年%s月%s日%s小时%s分钟%s秒钟' % (t.tm_year-1970, t.tm_mon-1, t.tm_mday-1, t.tm_hour, t.tm_min, t.tm_sec))



4.os和sys
1. os模块
os.sep 文件路径分隔符
os.makedirs("file/file2") 可生成多层递归目录
os.removedirs("file") 若目录温控,则删除,并递归到上一级目录,如若也为空,则删除,以此类推
os.mkdir('file') 生成单级目录;相当于shell中的mkdir dirname
os.rmdir('file') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中的 rmdir dirname
os.listdir('file') 列出指定目录下的所有文件和子目录,包括影藏文件,并以列表方式打印
os.remove 删除一个文件
os.stat('path/filename') 获取文件/目录信息
os.system("bash command") 运行shell命令,直接显示
os.popen("bash command).read() 运行shell命令,获取执行结果
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname") 改变当前脚本工作目录;相当于shell下c

os.path
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path) 如果path是绝对路径,返回True
os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数 将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后访问时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
os.path.getsize(path) 返回path的大小

特殊属性:
os.sep 输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep 输出当前平台使用的行终止符,win下为"\r\n",Linux下为"\n"
os.pathsep 输出用于分割文件路径的字符串 win下为;,Linux下为:
os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'

os.star
# 特殊属性:
st_mode: inode 保护模式 st_ino: inode 节点号。
st_dev: inode 驻留的设备。
st_nlink: inode 的链接数。
st_uid: 所有者的用户ID。
st_gid: 所有者的组ID。
st_size: 普通文件以字节为单位的大小;包含等待某些特殊文件的数据。
st_atime: 上次访问的时间。 st_mtime: 最后一次修改的时间。
st_ctime: 由操作系统报告的"ctime"。在某些系统上(如Unix)是最新的元数据更改的时间,在其它系统上(如Windows)是创建时间(详细信息参见平台的文档)。

2. sys模块 所有和python解释器相关的都在sys模块
sys.path python查找模块的路径
sys.argv 命令行参数List,第一个元素是程序本身路径
sys.exit(n) 退出程序,正常退出时exit(0),错误退出sys.exit(1)
sys.version 获取Python解释程序的版本信息
sys.platform 返回操作系统平台名称

猜你喜欢

转载自www.cnblogs.com/EuanXu/p/9960648.html