您的当前位置:首页正文

Python 之内建模块整理

来源:东饰资讯网

个人笔记、持续更新

Collections

  • from collections import Iterable:eg - isinstance([1, 3, 5], Iterable)
  • from collections import Iterator:能被 next() 执行的为 Iterator,为惰性计算。

random

  • random.choice(['apple', 'pear', 'banana']) -> 'apple'
  • random.sample(range(100), 10) -> [30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
  • random.random() -> random float
  • random.randrange(6) -> random integer chosen from range(6)

types:存储所以内置的 class 类型

  • types. FunctionType:自定义函数 class 类型
  • types. BuiltinFunctionType
    eg: type(abs)==types.BuiltinFunctionType -> True

os:与操作系统交互

  • os.listdir('.') -> 列出当前目录的文件名
  • os.getcwd() -> 返回当前文件的工作目录
  • os.chdir('/Users/mark/Desktop/...') -> 修改当前目录的工作环境
  • os.system('mkdir today') -> 执行系统命令
  • os.urandom(num) -> 产生 num 位 unicode 字符

shutil:提供常用的文件和目录操作方法

  • shutil.copyfile('data.db', 'archive.db')
  • shutil.move('/build/executables', 'installdir')

glob:从目录通配符搜索中生成文件列表

  • glob.glob('*.py') -> ['primes.py', 'random.py', 'quote.py']

sys:命令行参数

  • sys.argv:以 list 形式返回运行文件所在的目录
  • sys.path:以 list 形式返回

re:正则

  • re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') -> ['foot', 'fell', 'fastest']
  • re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') -> 'cat in the hat'

from datetime import date

  • date.today() -> '2019-01-28'
  • (date.today() - date(1991, 3, 22)).days -> 10174

zlib:数据压缩

  • -> 压缩字符串
  • zlib.decompress(tStr) -> 解压缩字符串
显示全文