Python 常用库

1. 运算符

2. 内置函数

3. 标准库

 

 

1. 运算符

运算符 Python表达式 结果 描述 支持的数据类型
+  [1, 2] + [3, 4] [1, 2, 3, 4] 合并 字符串、列表、元组
* "Hi!" * 4 Hi!Hi!Hi!Hi! 复制 字符串、列表、元组
in  3 in (1, 2, 3) True 元素是否存在 字符串、列表、元组、字典
not in 4 not in (1, 2, 3) True 元素是否不存在 字符串、列表、元组、字典

 示例:

 1 >>> # +
 2 >>> "abc" + "def"
 3 'abcdef'
 4 >>> [1, 2] + [2, 3]
 5 [1, 2, 2, 3]
 6 >>> (1, 2) + (2, 3)
 7 (1, 2, 2, 3)
 8 >>> 
 9 >>> # *
10 >>> "abc" * 4
11 'abcabcabcabc'
12 >>> [1, 2] * 4
13 [1, 2, 1, 2, 1, 2, 1, 2]
14 >>> (1, 2) * 4
15 (1, 2, 1, 2, 1, 2, 1, 2)
16 >>> [(1, 2), (2, 2)] * 2
17 [(1, 2), (2, 2), (1, 2), (2, 2)]
18 >>>
19 >>># in / not in 
20 >>> 1 in [1, 2]
21 True
22 >>> 1 in {2: 1, 3: 4} # 判断的是字典的键
23 False
24 >>> 2 in {2: 1, 3: 4}  
25 True

注意:+= 可以合并列表和元组的元素,但 + 不能。

1 >>> a = [1, 2]
2 >>> a += (3, 4)
3 >>> a
4 [1, 2, 3, 4]
5 >>>
6 >>> a = a + (3, 4)
7 Traceback (most recent call last):
8   File "<stdin>", line 1, in <module>
9 TypeError: can only concatenate list (not "tuple") to list

 

2. 内置函数

Python中查看内置函数的方法:

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'b', 'di', 'keyword', 's']
>>> dir(__builtins__)  # 查看内置函数

len()

在操作字典数据时,返回的是键值对的个数。

del

del 有两种用法,一种是del加空格,另一种是del()。

 1 >>> max(["a", 1, 2])  # max() 函数无法比较不同类型的数据
 2 Traceback (most recent call last):
 3   File "<stdin>", line 1, in <module>
 4 TypeError: '>' not supported between instances of 'int' and 'str'
 5 >>> max([1, 2])
 6 2
 7 >>> max(["a", "b"])
 8 'b'
 9 >>> max([[1, 2], [2, 3]])  # 多维列表/元组的比较,仅比较首元素
10 [2, 3]
11 >>> max([[1, 2], [2, 1]])
12 [2, 1]
13 >>> max([[1, 2], [2]])
14 [2]

eval() 与 exec()

两者均可将字符串转换成表达式,其区别如下:

# exec
>>> exec("a=1")
>>> b = exec("c=1")  
>>> b  # exec()本身没有返回值
>>> c  # 字符串表达式中可定义返回值
1
>>> a
1
>>>

# eval
>>> d = eval("1")
>>> d  eval()本身有返回值
1
>>> eval("e=1")  # 表达式中不可定义返回值
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    e=1
     ^
SyntaxError: invalid syntax

 

3. 标准库

Python有一套很有用的标准库(standard library)。标准库会随着Python解释器,一起安装在你的电脑中,它是Python的一个组成部分。

常用标准库

标准库说明
builtins 内建函数默认加载
os 操作系统接口
sys Python自身的运行环境
functools 常用的工具
json 编码和解码 JSON 对象
logging 记录日志,调试
multiprocessing 多进程
threading 多线程
copy 拷贝
time 时间
datetime 日期和时间
calendar 日历
hashlib 加密算法
random 生成随机数
re 字符串正则匹配
socket 标准的 BSD Sockets API
shutil 文件和目录管理
glob 基于文件通配符搜索

  

3.1 数学计算:math

math 模块提供了许多对浮点数的数学运算函数。

 1 >>> import math
 2 >>> dir(math)  # 查看math模块的方法
 3 ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
 4 >>> math.floor(1.3)  # 向下取整
 5 1
 6 >>> math.ceil(1.3)  # 向上取整
 7 2
 8 >>> math.sqrt(100)  # 平方根
 9 10.0
10 >>> math.pow(10, 3)  # 10的3次方
11 1000.0
12 >>> math.fabs(-1)  # 绝对值
13 1.0

 

3.2 随机数生成:random

random提供了生成随机数的工具,常用方法如下:

  • random():返回随机生成的一个实数,它在 [0, 1) 范围内。
  • randint(a, b):用于生成一个指定范围 [a, b] 间的整数。
  • randrange(a, b, c):以 c 为步长,随机生成 [a, b) 间的整数。
  • uniform(a, b):随机生成 [a, b] 间的浮点数。
  • choice(x):随机选取序列 x 中的一个元素。
  • sample(x, num):随机选取序列 x 中的 num 个元素。
  • shuffle(x):对序列 x 中的元素顺序进行打乱。
 1 >>> import random
 2 >>> random.random()
 3 0.8626173237509037
 4 >>> random.randint(1, 10)
 5 8
 6 >>> random.randrange(1, 10)
 7 3
 8 >>> random.randrange(1, 11, 2)  # 返回奇数
 9 1
10 >>> random.uniform(1, 10)
11 4.971518666776693
12 >>> random.choice("abcd")
13 'b'
14 >>> random.choice([1, 2, 3])
15 2
16 >>> random.sample([1, 2, 3, 4], 2)
17 [2, 1]
18 >>> li = [1, 2, 3, 4]  
19 >>> random.shuffle(li)  # 在原列表中进行了顺序打乱
20 >>> li
21 [2, 4, 3, 1]

  

 3.3 文件通配符:glob

glob模块提供了一个函数用于从目录通配符搜索中生成文件列表。

 1 >>> import glob
 2 # 若传入绝对路径,则返回绝对路径
 3 >>> glob.glob("e:\\test\\*.txt")
 4 ['e:\\test\\1.txt', 'e:\\test\\2.txt']
 5 # 若传入相对路径,则返回相对路径
 6 >>> glob.glob("*.txt")
 7 ['code.txt', 'file1.txt']
 8 >>> glob.glob("test\\*.txt")
 9 ['test\\1.txt', 'test\\2.txt']
10 # 若无匹配项,则返回空列表
11 >>> glob.glob("test\\*.py")
12 []

 

3.4 日期和时间:time与datetime

datetime

获取各种时间值

 1 >>> from datetime import datetime
 2 >>>
 3 >>> datetime.today()
 4 datetime.datetime(2020, 7, 23, 17, 52, 15, 174937)
 5 >>> datetime.now()
 6 datetime.datetime(2020, 7, 23, 17, 52, 29, 393525)
 7 >>> datetime.today() == datetime.now()
 8 True
 9 >>> now = datetime.now()
10 >>> now.hour
11 17
12 >>> now.minute
13 53
14 >>> now.isoweekday()  # 返回的1至7代表周一至周日
15 4
16 >>> now.weekday()  # 返回的0-6代表周一至周日
17 3
18 
19 >>> # 时间戳 转 datetime
20 >>> import time
21 >>> datetime.fromtimestamp(time.time())
22 datetime.datetime(2020, 7, 23, 17, 55, 57, 21749)

日期类型与字符串类型互转

 1 >>> import datetime
 2 
 3 
 4 ## datetime 转 str
 5 >>> now_time = datetime.datetime.now()  # 获取datetime对象
 6 >>> now_time
 7 datetime.datetime(2020, 7, 23, 16, 57, 38, 547635)
 8 >>> datetime.datetime.strftime(now_time, "%Y-%m-%d")  # 自定义字符串格式
 9 '2020-07-23'
10 >>> datetime.datetime.strftime(now_time, "%Y-%m-%d %H:%M:%S")
11 '2020-07-23 16:57:38'
12 >>> datetime.datetime.strftime(now_time, "%A %B %d, %Y")
13 'Thursday July 23, 2020'
14 
15 
16 ## date 转 str
17 >>> str(datetime.datetime.now().date())
18 '2020-07-23'
19 
20 
21 ## str 转 datetime
22 >>> str_time = '2020-07-23 17:02:17'
23 >>> datetime.datetime.strptime(str_time, "%Y-%m-%d %H:%M:%S")  # 需与传入的字符串格式一致
24 datetime.datetime(2020, 7, 23, 17, 2, 17)
25 
26 
27 ## str 转 date
28 >>> str_date = str(datetime.datetime.now().date())
29 >>> datetime.datetime.strptime(str_date, "%Y-%m-%d")
30 datetime.datetime(2020, 7, 23, 0, 0)
31 >>> # 将此转成月份日份两位数格式
32 >>> text = "2020-1-1"  
33 >>> datetime.datetime.strptime(text, "%Y-%m-%d")
34 datetime.datetime(2020, 1, 1, 0, 0)
35 >>> time_obj = datetime.datetime.strptime(text, "%Y-%m-%d")
36 >>> datetime.datetime.strftime(time_obj, "%Y-%m-%d")
37 '2020-01-01'

需要注意的是,strptime() 的性能要比想象中的差很多,因为它是使用纯 python 实现,并且必须处理所有的系统本地设置。因此,如果要在代码中需要解析大量的日期并且已经知道了日期字符串的确切格式,可以自己实现一套解析方案来获取,以达到更好的性能。

比如,如果已经知道所有日期格式是 YYYY-MM-DD,可以像下面这样实现一个解析函数:

1 from datetime import datetime
2 
3 def parse_ymd(s):
4     year_s, mon_s, day_s = s.split('-')
5     return datetime(int(year_s), int(mon_s), int(day_s))

实际测试中,这个函数比 datetime.strptime() 快7倍多。如果要处理大量的涉及到日期的数据的话,可以使用此方案。

日期的比较运算

在 python 中,日期类型 date 和日期时间类型 datetime 是不能比较的。如果要比较,可以将 datetime 转换为 date,而 date 不能直接转换为 datetime。

 1 ## date 算术运算
 2 >>> s1 = "2020-01-01"
 3 >>> s2 = "2020-02-02"
 4 >>> d1 = datetime.datetime.strptime(s1, "%Y-%m-%d")
 5 >>> d2 = datetime.datetime.strptime(s2, "%Y-%m-%d")
 6 >>> d2 - d1
 7 datetime.timedelta(32)  # 相差的天数
 8 
 9 ## datetime 算术运算
10 >>> s1 = "2020-01-01 11:00:00"
11 >>> s2 = "2020-01-01 12:00:00"
12 >>> d1 = datetime.datetime.strptime(s1, "%Y-%m-%d %H:%M:%S")
13 >>> d2 = datetime.datetime.strptime(s2, "%Y-%m-%d %H:%M:%S")
14 >>> d2 - d1
15 datetime.timedelta(0, 3600)  # (相差的天数, 相差的秒数):可通过days和seconds属性获取具体数值对象
16 >>> s3 = "2020-01-01 11:00:00"
17 >>> s4 = "2020-01-02 12:00:00"
18 >>> d3 = datetime.datetime.strptime(s3, "%Y-%m-%d %H:%M:%S")
19 >>> d4 = datetime.datetime.strptime(s4, "%Y-%m-%d %H:%M:%S")
20 >>> d4 - d3
21 datetime.timedelta(1, 3600)
22 >>> (datetime.now().date() - datetime(2019,12,31).date()).days  # 获取数值:今天是本年的第几天
23 205
24 >>> (datetime.now() - datetime(2019,12,31,11,11,11)).seconds  # 相差秒数
25 34943
26 
27 ## 注意 time 类型无法直接进行算术运算
28 >>> datetime.datetime.now().time() - datetime.datetime.now().time()
29 Traceback (most recent call last):
30   File "<stdin>", line 1, in <module>
31 TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

datetime 和 date 类型可以直接做加1减1的操作:

>>> today = datetime.datetime.today().date()  # 今天的date
>>> today
datetime.date(2020, 7, 23)
>>> yesterday = today + datetime.timedelta(days=-1)  # 昨天的date
>>> yesterday
datetime.date(2020, 7, 22)
>>> tomorrow = today + datetime.timedelta(days=1)  # 明天的date
>>> tomorow
datetime.date(2020, 7, 24)

# 更详细的参数
>>> time_obj = datetime.datetime(2019, 5, 12, 12, 13, 14)
>>> # 依次为 "周" "天", "时","分","秒","毫秒","微秒"
... time_obj + datetime.timedelta(weeks=0, days=0, hours=0, minutes=0,  seconds=0, milliseconds=0, microseconds=0)
datetime.datetime(2019, 5, 12, 12, 13, 14)

time

1 >>> import time
2 >>>
3 >>> time.localtime()
4 time.struct_time(tm_year=2021, tm_mon=3, tm_mday=26, tm_hour=13, tm_min=22, tm_sec=41, tm_wday=4, tm_yday=85, tm_isdst=0)
5 >>> time.localtime().tm_year
6 2021
7 >>>
8 >>> time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
9 '2021-03-26 13:23:28'

  

3.5 与解释器交互:sys

1)给程序传参

E:\python_pra>python test.py hello 1 2
['test.py', 'hello', '1', '2']

应用示例2:传入文件路径并打印其内容

1 import sys
2 import os
3 
4 if os.path.exists(sys.argv[1]):
5     with open("%s"%sys.argv[1], encoding="utf-8") as f:
6         print(f.read())

执行效果:

1 E:\>python code.txt file.txt
2 123中文哈

2)标准输入/错误/输出

  • sys.stdout.write("xxx"):标准输出(等价于print)
  • sys.stderr.write("xxx"):标准错误输出
  • sys.stdin.readline(): 标准输入,即从键盘输入(等价于input)

标准输出标准错误输出(通常缩写为 stdout 和 stderr)是建立在每个UNIX系统内的管道(pipe)。当 print 某东西时,结果输出到 stdout 管道中;当程序崩溃并打印出调试信息时(像 Python 中的错误跟踪),结果输出到 stderr 管道中。通常这两个管道只与正在工作的终端窗口相联,所以当一个程序打印输出时,可以看到输出;并且当一个程序崩溃时,可以看到调试信息(如果在一个基于窗口的 Python IDE 系统上工作, stdout 和 stderr 缺省为“交互窗口”)。

 1 import sys
 2 
 3 # 示例1:切换输出到屏幕或文件
 4 print("first print")
 5 saveout = sys.stdout  # 标准输出的对象
 6 f_obj = open("out.log", "w")  # 文件对象
 7 sys.stdout = f_obj  # 标准输出指向了文件对象
 8 # 打印的内容会记录在文件中,而不是屏幕上
 9 print("stdout print1")
10 print("stdout print2")
11 sys.stdout = saveout  # 标准输出指向回标准输出对象
12 print("second print")  # 重新输出到屏幕上
13 f_obj.close()
14 
15 # 示例2
16 print('Fatal error: invalid  input!',file=open("e:\\log.out","w"))  # 输出到指定文件中
17 print('Fatal error: invali input! ',file=sys.stderr)  # 标准错误输出(屏幕)

3)终止程序

1 >>> import sys  
2 >>> sys.exit(0)  # 终止当前进程
3 
4 E:\>
5 
6 >>> import sys  
7 >>> sys.exit(1)  # 非正常退出
8 
9 E:\>

  

3.6 创建hash对象:hashlib

md5 算法

示例:

 1 >>> import hashlib
 2 >>> m = hashlib.md5()  # 创建一个md5 hash对象,得出一个128位的密文。md5(message-Digest Algorithm 5):消息摘要算法
 3 >>> print(m)
 4 <md5 HASH object @ 0x01D20200>
 5 >>> m.update("python")  # 注意Python3中的问题
 6 Traceback (most recent call last):
 7   File "<stdin>", line 1, in <module>
 8 TypeError: Unicode-objects must be encoded before hashing
 9 >>> m.update("python".encode("utf8"))  # 对字符串进行md5加密的更新处理,需要指定编码
10 >>> print(m.hexdigest())  # 返回十六进制加密结果
11 23eeeb4347bdd26bfc6b7ee9a3b755dd

应用场景:注册登录

 1 >>> import hashlib
 2 >>> import time
 3 >>>
 4 >>> value = "xiaoming"
 5 >>> m = hashlib.md5()
 6 >>> str = "{}{}".format(value, time.strftime("%Y-%m-%d", time.localtime()))
 7 >>>
 8 >>> m.update(str.encode("utf-8"))
 9 >>> final_value = m.hexdigest()
10 >>>
11 >>> print(final_value)
12 70e851c5a693b03915fc062eb611f6ad

sha1 算法

1 >>> from hashlib import sha1
2 >>> s = sha1()
3 >>> s.update("password".encode("utf-8"))
4 >>> pwd = s.hexdigest()
5 >>> pwd
6 '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8'

 

3.7 字符串获取:string

>>> import string
>>> 
>>> dir(string)
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']

>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'

>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

>>> string.digits
'0123456789'

>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

 

posted @ 2020-02-16 20:55  Juno3550  阅读(234)  评论(0编辑  收藏  举报