筱团Blog筱团のBlog

python 常用内建模块

筱团·2022-08-10 16:18·123 次阅读

python 常用内建模块

Prerequisite

参考文章:廖雪峰

包含:datetime、collections(parser:构造命令行参数)、base64、hashlib、hmac、itertools、contextlib、string

datetime#

注意:我没记录 本地时间转换为UTC时间 和 时区转换 的方法,需要的自行参考廖雪峰的文章

Copy
from datetime import datetime, timedelta # 获取当前 datetime # 默认是操作系统的时间,即北京时间 now = datetime.now() # 2022-08-09 15:57:49.629587 # 获取指定 datetime dt = datetime(2022, 4, 6, 6, 6, 6) # 2022-04-06 06:06:06 # datetime 转换 timestamp # timestamp(时间戳)是从 1970年1月1日 00:00:00 到当今的秒数 now.timestamp() # 1660032186.291992 # timestamp 转换 datetime t = 1660032186.291992 datetime.fromtimestamp(t) # 2022-08-09 16:03:06.291992 # str 转换 datetime cday = datetime.strptime('2022-08-09 16:03:06', '%Y-%m-%d %H:%M:%S') # 2022-08-09 16:03:06 # datetime 转换 str cnow = now.strftime('%Y-%m-%d %H:%M:%S') # 2022-08-09 16:09:07 # datetime 加减 # 直接在 timedelta 中进行运算 tomorrow = now + timedelta(hours = 24) # 2022-08-10 16:11:16.693899

collections#

Copy
# namedtuple 类似类的元组 from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(1, 2) p.x # 1 p.y # 2 # deque 队列 # deque 默认向右侧插入和删除 from collections import deque q = deque(['a', 'b', 'c']) q.append('x') q # deque(['a', 'b', 'c', 'x']) q.appendleft('y') q # deque(['y', 'a', 'b', 'c', 'x']) # 类似的函数还有 pop() 和 popleft() # defaultdict 自定义异常 from collections import defaultdict dd = defaultdict(lambda: 'N/A') dd['key1'] = 'abc' dd['key1'] # 'abc' dd['key2'] # 'N/A' # OrderedDict 有序字典 from collections import OrderedDict d = dict([('a', 1), ('b', 2), ('c', 3)]) od = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) d # {'a': 1, 'c': 3, 'b': 2} od # OrderedDict([('a', 1), ('b', 2), ('c', 3)]) # OrderedDict 的 Key 会按照插入的顺序排列,如 od['x'] = 1 # Counter 计数器 from collections import Counter c = Counter() c.update('hello') c # Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1}) # ChainMap 包含了多个字典的字典 # 适用场景:多种情况的传参 from collections import ChainMap import os, argparse # 构造缺省参数: defaults = { 'color': 'red', 'user': 'guest' } # 构造命令行参数: parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args() command_line_args = { k: v for k, v in vars(namespace).items() if v } # 组合成ChainMap: combined = ChainMap(command_line_args, os.environ, defaults) # 打印参数: print('color=%s' % combined['color']) print('user=%s' % combined['user']) # 没有任何参数时,打印出默认参数 $ python3 use_chainmap.py # color=red # user=guest # 当传入命令行参数时,优先使用命令行参数 $ python3 use_chainmap.py -u bob # color=red # user=bob # 同时传入命令行参数和环境变量,命令行参数的优先级较高 $ user=admin color=green python3 use_chainmap.py -u bob # color=green # user=bob

base64#

Copy
import base64 base64.b64encode(b'xxx') # 正常编码 base64.b64decode(b'xxx') # 正常解码 base64.urlsafe_b64encode(b'xxx') # 把字符 + 和 / 分别变成 - 和 _ base64.urlsafe_b64decode(b'xxx') # 同理

hashlib / hmac#

分别是计算哈希值和带盐的哈希值

Copy
# 计算哈希值 # 略 # 计算带盐哈希值 import hmac message = b'Hello, world!' key = b'secret' h = hmac.new(key, message, digestmod='MD5') h.hexdigest() # fa4ee7d173f2d97ee79022d1a7355bcf

itertools#

Copy
import itertools # count 无限自然数 natruals = itertools.count() for n in natruals: print(n, end=" ") # 0 1 2 3 ... # cycle 无限循环序列 cs = itertools.cycle('ABC') for c in cs: print(c, end=" ") # A B C A B C A B C ... # repeat 限定重复次数 ns = itertools.repeat('A', 3) for n in ns: print(n, end=" ") # A A A # takewhile 截取有限序列 natruals = itertools.count() ns = itertools.takewhile(lambda x: x <= 10, natruals) list(ns) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # chain 串联迭代对象成迭代器 for c in itertools.chain('ABC', 'XYZ'): print(c, end=" ") # A B C X Y Z # groupby 把迭代器中相邻的重复元素挑出来放在一起 for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()): print(key, list(group)) # A ['A', 'a', 'a'] # B ['B', 'B', 'b'] # C ['c', 'C'] # A ['A', 'A', 'a']

contextlib#

上下文管理器

  • 对于读写文件函数来说,事后要关闭函数,这就需要用到上下文管理器 with
  • 对于类来说,可以通过 __enter____exit__ 实现
  • 对于类和函数来说,都可以通过 @contextmanager 这个装饰器实现
Copy
from contextlib import contextmanager # 针对类 class Query(object): def __init__(self, name): self.name = name def query(self): print('Query info about %s...' % self.name) @contextmanager def create_query(name): print('Begin') q = Query(name) yield q print('End') with create_query('Bob') as q: q.query() """ Begin Query info about Bob... End """ # 针对函数 @contextmanager def tag(name): print("<%s>" % name) yield print("</%s>" % name) with tag("h1"): print("hello") print("world") """ <h1> hello world </h1> """ # 针对没有上下文的单个函数 from urllib.request import urlopen @contextmanager def closing(thing): try: yield thing finally: thing.close() with closing(urlopen('https://www.python.org')) as page: print('Begin') for line in page: print(line) print('End') """ Begin xxxxx xxxxx ... End """

string#

我之前都没注意到这个库这么好用!!

Copy
# string.ascii_lowercase abcdefghijklmnopqrstuvwxyz # string.ascii_letters abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ # string.ascii_uppercase ABCDEFGHIJKLMNOPQRSTUVWXYZ # string.digits 0123456789 # string.hexdigits 0123456789abcdefABCDEF # string.octdigits 01234567 # string.printable 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ + " \t\n" + chr(13) + chr(11) + chr(12) # string.punctuation !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ + " \t\n" + chr(13) + chr(11) + chr(12) # string.whitespace " \t\n" + chr(13) + chr(11) + chr(12)
posted @   筱团  阅读(123)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示
目录