一、typing模块
typing模块:提供了Generator,Iterable,Iterator三种数据类型,用来约束函数
def self_add(x: int, y: int):
return x + y
res = self_add(10, 20)
print(res)
from typing import Generator,Iterable,Iterator
def func(g: Generator):
return g
def ger():
yield
res = func(ger())
print(res)
二、re模块
re模块:从字符串里找特定的字符串
# re模块:从字符串里找特定的字符串
import re
# re的基本语法(匹配规则)
s = '王大炮打炮被大炮打死了 王大炮打炮被大炮打死了'
# ^:开始
print(re.findall('^王大炮', s))
# $:结尾
print(re.findall('死了$', s))
# []:匹配中间的字符,只要单个字符
s = 'acefghjkacefsdfsdf'
print(re.findall('[acef]', s)) # 只要单个字符
# []+^连用:^对[]内的元素取反
print(re.findall('[^acef]', f))
# .:任意字符(除了
)
s = 'abacadaeaf'
print(re.findall('a.', s))
s = 'abaacaaaaa'
# *:前面的字符0-无穷个
print(re.findall('a*', s))
# +:前面的字符1-无穷个
print(re.findall('a+', s))
# ?:前面字符0-1个
print(re.findall('a?', s))
# {m}:前面字符m个
print(re.findall('a{5}', s))
# {n, m}:前面字符n-m个
print(re.findall('a{2,5}', s))
# d:数字
s = 's 1 s+
=$ 2_s 3'
print(re.findall('d', s))
# D:非数字
print(re.findall('D', s))
# w:数字/字母/下划线
print(re.findall('w', s))
# W:非数字/字母/下划线
print(re.findall('W', s))
# s:空格/ /
print(re.findall('s', s))
# S:非空格/ /
print(re.findall('S', s))
# .*: 贪婪模式(最大化),找到继续找,让结果最大化
s = 'abbbcabc'
print(re.findall('a.*c', s))
# .*?: 非贪婪模式(最小化),找到就马上停止
print(re.findall('a.*?c', s))
# (): 只要括号内的
s = 'abacad'
print(re.findall('a(.)', s))
# A|B: A和B都要
s = 'abacad'
print(re.findall('a|b', s))
三、collections模块
collections模块:复杂的数据类型
# 有名的元组
from collections import namedtuple
point = namedtuple('point',['x','y'])
p = point(1,2)
print(p.x)
print(p.y)
# 默认字典
from collections import defaultdict
# dic = {'a':1}
# print(dic['b'])
dic = defaultdict(lambda :'nan') # dic = {} # 如果找不到赋了一个默认值
dic['a'] = 1
print(dic['a'])
print(dic['c'])
# 双端队列
# lis = [1,2,3] # 线性表
# lis.append(4)
# print(lis)
from collections import deque # 链表
de = deque([1,2,3])
de.append(4)
print(de)
de.appendleft(0)
print(de)
de.popleft()
de.popleft()
print(de)
# 计数器
from collections import Counter
s= 'programming'
# dic = {}
# for i in s:
# if i in dic:
# dic[i]+=1
# else:
# dic[i] =1
# print(dic)
c = Counter() # 字典
for i in s:
c[i] +=1
print(c)