脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 内置模块详解

python 内置模块详解

2021-05-10 00:23沐小熊 Python

模块是一个保存了Python代码的文件。模块能定义函数,类和变量。模块里也能包含可执行的代码,今天我们就来详细探讨下python内置的一些常用模块

一.random模块  随机      

random()    随机小数           
uninform(a,b) 随机小数
randint(a,b)  随机整数
choice() 随机选择一个
sample() 随机选择多个
shuffle() 打乱

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import random
from random import randint
 
print(randint(10, 20))
# print(random.randint(10, 20))/
print(random.random())
print(random.uniform(10, 20)) # 10-20的随机小数
 
lst = ['宝宝', '宝浪', '宝强', '包拯']
random.shuffle(lst) # 随机打乱顺序
print(lst)
 
# 从列表中随机选择一个
print(random.choice(["林志玲", "刘一菲", "王昭君", "艾米", "宝宝"]))
print(random.sample(["林志玲", "刘一菲", "王昭君", "艾米", "宝宝"],3)) # 可以给随机选取几个

二.Counter 计数

?
1
2
3
4
5
6
7
from collections import Counter
 
print(Counter('宝宝今年特别喜欢王宝强')) # 计数
 
lst = ['jay', 'jay', 'jay', '宝宝', '宝宝', '胡辣汤', '上官婉儿']
c = Counter(lst)
print(c.get('宝宝'))

三.字典

1.默认值字典

?
1
2
3
4
5
6
7
from collections import defaultdict
 
dd = defaultdict(lambda: '胡辣汤') # callable 可调用的, 字典是空的
 
print(dd['张无忌']) # 从字典向外拿数据. 字典是空的. key:callable()
print(dd['宝宝']) # 这里的[] 和get() 不是一回事儿
print(dd)

2.有序字典

?
1
2
3
4
5
6
7
8
9
from collections import OrderedDict
 
dic = OrderedDict() # 有序字典
dic['a'] = '哈哈'
dic['b'] = '呵呵'
print(dic)
print(dic.get('a'))
print(dic.values())
print(dic['a'])

四.栈和队列

1.栈

特点:先进后出

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class StackFullException(Exception):
  pass
 
class StackEmptyException(Exception):
  pass
class Stack:
 
  def __init__(self,size):
    self.size = size 给定存放数据的长度
    self.lst = [] # 存放数据的列表
    self.top = 0 # 栈顶指针
 
  # 入栈
  def push(self, el):
    if self.top >= self.size:
      raise StackFullException('your stack is full!!')
    self.lst.insert(self.top, el) # 放元素
    self.top += 1 # 栈顶指针向上移动一下
 
  # 出栈
 
  def pop(self):
    if self.top == 0:
      raise StackEmptyException('your stack is empty!!!')
    self.top -= 1
    el = self.lst[self.top]
    return el
 
s = Stack(6)
s.push('宝宝')
s.push('我还')
s.push('记得')
 
print(s.pop())
print(s.pop())
print(s.pop())

2.单项队列

特点:先进先出

?
1
2
3
4
5
6
7
8
9
10
11
12
13
import queue
q = queue.Queue()
q.put('李嘉诚1')
q.put('李嘉诚2')
q.put('李嘉诚3')
q.put('李嘉诚4')
q.put('李嘉诚5')
 
print(q.get())
print(q.get())
print(q.get())
print(q.get())
print(q.get())

3.双向队列

特点:和单项一样

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from collections import deque
 
d =deque() # 创建双向队列
d.append('宝宝') # 在右侧添加
d.append('no')
d.append('way')
d.append('哈哈')
d.appendleft('娃哈哈') # 在左边添加
d.appendleft('爽歪歪')
d.appendleft('优酸乳')
 
print(d.pop()) # 从右边拿数据
print(d.pop()) # 从右边拿数据
print(d.pop()) # 从右边拿数据
print(d.pop()) # 从右边拿数据
print(d.popleft()) # 从左边拿数据
print(d.popleft()) # 从左边拿数据
print(d.popleft()) # 从左边拿数据

五.time模块

 # 时间戳: 从1970-01-01 00:00:00 开始计算. 未来存储的时候用时间戳
 print(time.time()) 

 # 格式化时间
 print(time.strftime('%Y-%m-%d %H:%M:%S'))  # 用来显示的

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

 # 数据库里存储一个数字. 把它还原成我们的格式化时间
 a = 847772281.0
 # 先把这个时间戳转换成python中的结构化时间
 t = time.localtime(a)  # 结构化时间括号里填的是秒 time.localtime(秒) # 本地化的东八区的时间
 # t = time.gmtime(a)  # 格林尼治时间
 
 s = time.strftime('%Y-%m-%d %H:%M:%S', t)  # time.strftime(格式化格式, 传入结构化转化完的时间 t)
 print(s)

# 让用户输入一个时间. 然后把时间转化成时间戳
strt = input('请输入一个时间:')
# 把字符串转化成结构化时间
t = time.strptime(strt, '%Y-%m-%d %H:%M:%S')
# 转化成时间戳
print(time.mktime(t))  # 847772281.0  # 本地化的东八区的时间

六.functools

1.wraps

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from functools import wraps # 可以改变一个函数的名字, 注释....
 
 
def wrapper(fn):
  @wraps(fn) # 把inner的名字改变成原来的func
  def inner(*args, **kwargs):
    print('前')
    ret = fn(*args,**kwargs)
    print('后')
    return ret
  return inner
 
@wrapper # func = wrapper(func)
def func():
  print('哈哈哈')
 
print(func.__name__) # func

2.reduce

?
1
2
3
4
5
6
7
8
def func(a, b):
  return a + b # 0 + 1
 
# 会把我们每一个数据交给func去执行, 把默认值作为第一个参数传递给函数
 
ret = reduce(func, [1, 4, 7, 8, 6, 9],0)
print(ret)
print(reduce(lambda x, y: x+y, [i for i in range(101)]))

3.partial

?
1
2
3
4
5
6
7
8
9
from functools import partial
 
def chi(zhushi, fushi):
  print(zhushi, fushi)
 
chi2 = partial(chi, fushi = "辣鸡爪")
chi2('大米饭')
chi2('小米饭')
chi2('黑米饭')

七.命名元组 namedtuple

?
1
2
3
4
5
6
p = namedtuple('Point', ["x", "y"])
 
p1 = p(10, 20)
print(p1)
print(p1.x)
print(p1.y)

八.OS模块 系统操作

1.os

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 必须要记住. 很常用
os.makedirs('baby/安哥拉/特斯拉') # 可以一次性创建多级目录
 
os.mkdir('baby/安哥拉/特斯拉/bb') # 上层文件夹必须存在
 
os.removedirs('baby/安哥拉/特斯拉/bb') # 目录不是空, 不能删除 #可以帮我们删除当前这个目录级中的所有空文件夹
 
# 可以记住 一般不删数据
os.rmdir('baby/安哥拉/特斯拉') # 指定文件夹删除
 
os.system('dir')
print(os.popen('dir').read()) # 执行shell脚本或者cmd命令
 
print(os.getcwd()) # 当前程序运行的文件夹 D:\python_workspace_s18\day 23 内置模块02
 
os.chdir('baby')
 
 # os.path 和路径相关的内容
 print(os.path.abspath('baby')) # 把相对路径改成绝对路径
 print(os.path.split(r'D:\python_workspace\内置模块\baby\1.txt')) # 切割文件和文件路径
 
 print(os.path.dirname(r'D:\python_workspace\内置模块\baby\1.txt'))
 # 文件路径
 print(os.path.basename(r'D:\python_workspace\内置模块\baby\1.txt'))
 # 文件
 
 print(os.path.existsr'D:\python_workspace\内置模块\baby\1.txt'))
 # 判断文件是否存在
 print(os.path.abspath('1.txt'))

2.sys模块

?
1
2
3
4
5
import sys
 
print(sys.path) # 找到模块的. 必须要记住. 模块的搜索路径
sys.path.append(r'D:\python_workspace\内置常用模块')
print(sys.path)

九.自定义模块和包

import   

from xxx import xxxx   

一个表达式 -> 一条语句  -> 语句块  -> 函数 -> 类  -> 模块  -> 包  -> 项目       

包就是我们的文件夹, 包内可以写很多个模块.

查找路径是:sys.path, 随动. 跟着你的启动文件所在的位置变化       

不论使用绝对导入. 还是相对导入. 启动文件一定在最外面

 1.模块

写的一个py文件就可以称作一个模块

2.包

文件夹里装很多模块的就是包

原文链接:https://www.cnblogs.com/beargod/p/10202308.html

延伸 · 阅读

精彩推荐