python常用标准库

mac2025-06-10  42

1. math–数学函数(第三方标准库)

作用:提供特殊的数学运算

>>> import math >>> math.e 2.718281828459045 >>> math.e,math.pi (2.718281828459045, 3.141592653589793) >>> math.ceil(3.4) #返回x上限最小的整数 4 >>> math.ceil(3.6) 4 >>> math.floor(3.6) 3 >>> math.degrees(3.14) #将角x从弧度转换成角度 179.9087476710785 >>> math.radians(180) # 将角度转换成弧度 3.141592653589793

更过的math库中的函数可以参考:math — 数学函数¶

2. os模块(操作系统对象函数)

>>> import os >>> os.getcwd() # 返回当前工作目录 'C:\\Users\\xiao' >>> path = os.getcwd() >>> os.listdir(path) # 返回path目录下所有文件列表 ['.anaconda', '.bash_history', '.conda', '.condarc', '.git', '.gitconfig', '.ipython', '.keras', '.matplotlib', '.PyCharmCE2018.2', '3D Objects', 'AppData', 'Application Data', 'Contacts', 'Cookies', 'Desktop', 'Documents', 'Downloads', 'Favorites', 'fpfftResultsFile.txt', 'IntelGraphicsProfiles', 'java_error_in_pycharm_9496.log', 'Links', 'Local Settings', 'MicrosoftEdgeBackups', 'Music', 'My Documents', 'NetHood', 'NTUSER.DAT', 'ntuser.dat.LOG1', 'ntuser.dat.LOG2', 'NTUSER.DAT{58f1b21f-bb60-11e9-9229-b025aa0f218a}.TM.blf', 'NTUSER.DAT{58f1b21f-bb60-11e9-9229-b025aa0f218a}.TMContainer00000000000000000001.regtrans-ms', 'NTUSER.DAT{58f1b21f-bb60-11e9-9229-b025aa0f218a}.TMContainer00000000000000000002.regtrans-ms', 'ntuser.ini', 'OneDrive', 'Pictures', 'PrintHood', 'Recent', 'Saved Games', 'Searches', 'SendTo', 'Templates', 'Videos', '「开始」菜单'] >>> os.path.getsize(path) # 返回文件的大小,若是目录则返回0 12288 >>> os.path.exists(path) # 判断path是否存在,存在返回True,不存在返回False True >>> os.path.isdir(path) # 判断path是否是目录,是返回True,不是返回False True >>> os.walk(path) # 递归返回path下的目录(包括path目录)、子目录、文件名的三元组 <generator object walk at 0x0000019323B24E58>

各种os库函数接口:os — 各种各样的操作系统接口¶

3. random模块常用函数

>>> import random >>> random.choice(['c','c++','python','R']) 'c++' >>> random.randint(1,100) # 返回随机整数 N 满足 a <= N <= b。相当于 randrange(a, b+1)。 2 >>> random.random() # 返回 [0.0, 1.0) 范围内的下一个随机浮点数。 0.3578168510514578 >>> random.uniform(5,10) # 返回一个随机浮点数 N ,当 a <= b 时 a <= N <= b ,当 b < a 时 b <= N <= a 。 9.643286356696208 >>> random.sample(range(100),10) # 返回从总体序列或集合中选择的唯一元素的 k(10) 长度列表。 用于无重复的随机抽样。 [7, 2, 88, 34, 6, 53, 30, 65, 26, 9] >>> list=[4,2,5,7,34,3,5] >>> random.shuffle(list) # 将序列list随机打乱位置 >>> >>> list [3, 2, 4, 34, 5, 7, 5]

更多random库函数参考:random — 生成伪随机数¶

4. datetime模块

>>> import datetime >>> from datetime import time >>> time(23,20,35) datetime.time(23, 20, 35) >>> from datetime import datetime >>> datetime.now() datetime.datetime(2019, 11, 1, 14, 27, 51, 396233) >>> dt = datetime.now() >>> dt.strftime('%a, %b %d %Y %H:%M') 'Fri, Nov 01 2019 14:28' >>> dt = datetime(2019,10,1,14,11) >>> ts = dt.timestamp() >>> ts 1569910260.0 >>> datetime.fromtimestamp(ts) datetime.datetime(2019, 10, 1, 14, 11)

datetime函数库:datetime — 基本的日期和时间类型¶

最新回复(0)