Python作为一种高级编程语言,广泛应用于各个领域的软件开发中。除了其简洁、易于理解和学习的语法外,Python还内置了许多强大的模块,这些模块提供了各种功能和工具,能够极大地提升开发效率。本文将介绍几个常用的Python内置模块以及它们的用途。
一、math模块
提供了数学相关的函数和常量,如数学运算、三角函数、指数函数、对数函数等。
import math
# 常用的常量
print(math.e)
print(math.pi)
x = 3.14
# 向上取整
math.ceil(x)
# e的x次方
math.exp(x)
# 向下取整
math.floor(x)
iterable = [1, 2, 3, 4, 5]
# 求和
math.fsum(iterable)
x = 4
y = 6
# 求最大公约数
math.gcd(x, y)
# x的y次方
math.pow(x, y)
# 所有元素的乘积
math.prod(iterable)
二、time模块
time模块提供了时间相关的函数,使得我们可以在程序中轻松处理时间。通过time模块,我们可以获得当前时间、格式化时间、延迟执行等操作。
import time
# 时间戳,单位是秒
ticks = time.time()
print("当前时间戳为:", ticks)
# localtime是一个对象
localtime = time.localtime(time.time())
print("本地时间为 :", localtime)
print("本地时间的年 :", localtime.tm_year)
print("本地时间的月 :", localtime.tm_mon)
print("本地时间的日 :", localtime.tm_mday)
print("本地时间的时 :", localtime.tm_hour)
print("本地时间的分 :", localtime.tm_min)
print("本地时间的秒 :", localtime.tm_sec)
print("本地时间,一周的第几天 :", localtime.tm_wday)
print("本地时间,一年的第几天 :", localtime.tm_yday)
# asctime函数返回默认的时间格式的字符串:Mon Jun 19 23:17:09 2023
localtime = time.asctime(time.localtime(time.time()))
print("本地时间为 :", localtime)
# strftime可以自定义时间格式:2023-06-19 23:17:09
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
# strptime将时间字符串转为时间对象
print(time.strptime("2023-06-19 23:17:09", "%Y-%m-%d %H:%M:%S"))
# 线程睡眠5s
time.sleep(5)
三、datetime模块
datetime模块也是时间处理模块,相比time模块,它提供了更加丰富的功能,包括日期和时间的表示、计算、格式化等功能。
from datetime import datetime, timedelta, timezone
# 从datetime对象中读取年月日时分秒
now = datetime.now()
print(now)
print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)
print(now.microsecond)
# 用指定日期时间创建datetime
dt = datetime(2023, 6, 20, 12, 20)
print(dt)
# datetime对象和时间戳互相转换
ts = dt.timestamp()
print(ts)
dt = datetime.fromtimestamp(ts)
print(dt)
# datetime格式化
dt = datetime.strptime('2023-06-20 18:19:59', '%Y-%m-%d %H:%M:%S')
print(dt)
str_time = dt.strftime('%Y-%m-%d %H:%M:%S')
print(str_time)
# 时间加减
dt = dt + timedelta(hours=28)
print(dt)
# 时区转换
tokyo_dt = dt.astimezone(timezone(timedelta(hours=9)))
print(tokyo_dt)
四、random模块
random模块提供了生成随机数的函数,这在软件开发中经常会用到。通过random模块,我们可以生成随机整数、浮点数、从列表中随机选择等等操作。
import random
# 返回[0,1)之间的一个浮点数
rand = random.random()
print(rand)
# 返回[1,10)之间的一个浮点数
rand = random.uniform(1, 10)
print(rand)
# 返回[1,10)之间的一个整数
rand = random.randint(1, 10)
print(rand)
# 从容器中选择一个元素
rand = random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9])
print(rand)
rand = random.choice(["aa", "bb", "cc"])
print(rand)
# 从容器中选择多个元素
samples = random.sample([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
print(samples)
# 打乱原来容器的元素顺序
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(numbers)
print(numbers)
五、json模块
提供了JSON(JavaScript Object Notation)的编码和解码功能,用于处理JSON数据格式。
import json
content = '''
{ "store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
'''
# loads函数的参数是字符串
store_items = json.loads(content)
# 用方括号访问的方式,如果key不存在,会报错
print(store_items["store"]["bicycle"])
print(store_items["store"]["bicycle"]["color"])
# 用get函数,可以设置默认值,不会报错
print(store_items.get("store", {}).get("bicycle", {}).get("color", ""))
# json对象转为字符串
content2 = json.dumps(store_items)
print(content2)
with open("/Users/user/Downloads/store_items.json", "r") as f:
# load函数的参数是文件
store_items = json.load(f)
with open("/Users/user/Downloads/store_items_dump.json", "w") as f:
# json对象转为字符串并写入到文件中,可以设置缩进
json.dump(store_items, f, indent=4)
六、collections模块
这个模块在list、tuple、set、map的基础上,提供了很多更高级的容器。
from collections import namedtuple, deque, defaultdict, OrderedDict, ChainMap
# 命名的元组,用来表示一些简单的定义,比如点、三角形等等
Point = namedtuple('Point', ['x', 'y'])
point = Point(3, 4)
print(point.x, point.y)
# 双端队列,相比list有更高效的插入和删除性能
dq = deque([1, 2, 3])
dq.append(4)
dq.appendleft(0)
print(dq)
dq.pop()
dq.pop()
dq.popleft()
print(dq)
# 设置一个默认值,如果没有key,就返回默认值,基础的字典结构是会报错的
dd = defaultdict(lambda: "null")
dd["name"] = "zhangsan"
print(dd["name"])
print(dd["age"])
# key-value会按照插入时的顺序,即使访问key、对key做更新也不会改变
od = OrderedDict()
od["name"] = "zhangsan"
od["age"] = 18
od["sex"] = "male"
print(od.keys())
od.get("age")
od["age"] = 20
print(od.keys())
# 按顺序查找多个map,找到就返回
map1 = {"name": "zhangsan", "age": 18}
map2 = {"name": "lisi", "age": 20, "sex": "male"}
map3 = {"name": "wangwu", "age": 22, "sex": "female"}
cm = ChainMap(map1, map2, map3)
print(cm.get("name"))
print(cm.get("sex"))
七、csv模块
csv(Comma-Separated Values)是一种常见的数据交换格式,被广泛用于数据存储和传输。Python提供了内置的csv模块,使得CSV文件的读写和处理变得简单高效。
csv文件是一种以逗号为分隔符的纯文本文件,每一行代表一条记录,每个字段由逗号或其他自定义分隔符分隔。CSV文件通常用于存储结构简单的表格数据,如Excel表格的导出和导入。
csv文件的读取
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
next(reader)
for row in reader:
print(row[0], row[1])
data.csv的内容如下:
name,age
zhangsan,20
lisi,30
csv文件的写入
import csv
data = [
['Name', 'Age', 'Email'],
['John', 30, 'john@example.com'],
['Alice', 25, 'alice@example.com'],
['Bob', 35, 'bob@example.com']
]
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
自定义分隔符
import csv
data = [
['Name', 'Age', 'Email'],
['John', 30, 'john@example.com'],
['Alice', 25, 'alice@example.com'],
['Bob', 35, 'bob@example.com']
]
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file, delimiter=';', quoting=csv.QUOTE_ALL)
writer.writerows(data)
八、functools
当谈到处理函数时,Python的functools
模块提供了许多有用的工具,可以帮助我们更好地操作函数。这个模块提供了一些高阶函数和装饰器,用于函数的操作、转换和优化。在本篇博客中,我们将深入探讨functools
模块的一些主要功能,并通过实例演示它们的应用。
1. partial
函数
partial
函数允许我们固定一个函数的部分参数,然后返回一个新的函数,这个新函数的调用可以像原函数一样。这在需要多次调用同一个函数,但部分参数保持不变的情况下非常有用。
from functools import partial
def power(base, exponent):
return base ** exponent
# 固定base参数为2,创建一个新的函数
square = partial(power, 2)
print(square(3)) # 输出 2 ** 3,即 8
2. cmp_to_key
函数
cmp_to_key
函数用于将比较函数转换为一个可以用于排序的键函数。这在需要自定义排序规则时非常有用,例如对复杂对象进行排序。
from functools import cmp_to_key
def compare_lengths(a, b):
return len(a) - len(b)
words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key=cmp_to_key(compare_lengths))
print(sorted_words) # 输出 ['date', 'apple', 'banana', 'cherry']
3. lru_cache
函数
lru_cache
函数是一个装饰器,用于为函数提供一个缓存,以存储最近使用的函数调用的结果。这可以加速函数的执行,尤其是对于重复调用相同参数的情况。
from functools import lru_cache
@lru_cache(maxsize=None) # 缓存所有调用结果
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(10)) # 输出 55
total_ordering
类装饰器
total_ordering
是一个类装饰器,用于自动生成类的比较操作方法,如__eq__
、__lt__
等。这可以减少实现自定义比较方法的代码量。
from functools import total_ordering
@total_ordering
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def __eq__(self, other):
return self.area() == other.area()
def __lt__(self, other):
return self.area() < other.area()
rect1 = Rectangle(3, 4)
rect2 = Rectangle(4, 5)
print(rect1 == rect2) # 输出 False
print(rect1 < rect2) # 输出 True
functools
模块提供了一些非常有用的函数,用于处理函数和类的操作。在实际编程中,这些函数可以帮助我们优化代码、减少重复工作、增加代码的可读性,并提高性能。通过熟练掌握functools
模块的各种功能,你可以更好地利用Python的特性,编写出高效且优雅的代码。