欢迎来到我的个人博客,有Python技术,自媒体,创业,APP开发问题随时讨论交流

Python中9个鲜为人知的宝藏标准库

Python sitin 7个月前 (09-27) 321次浏览 已收录 0个评论

Python中9个鲜为人知的宝藏标准库

大家好,我是涛哥,今天给大家分享 Python中9个鲜为人知的宝藏标准库,内容3000字,阅读大约7分钟。

Python作为一门强大的编程语言,拥有丰富的标准库,其中一些模块虽然不太为人熟知,但却是解决各种问题的宝藏。在本文中,我们将介绍一些鲜为人知但非常实用的Python标准库,以及如何使用它们。

1. collections:高级容器数据类型

collections模块提供了许多有用的数据类型,如Counter、deque和defaultdict。

from collections import Counter, deque, defaultdict

# 使用Counter统计列表中元素出现次数
my_list = [1223334444]
counter = Counter(my_list)
print(counter)

# 使用deque创建双向队列
my_deque = deque([123])
my_deque.append(4)  # 在右侧添加元素
my_deque.appendleft(0)  # 在左侧添加元素
print(my_deque)

# 使用defaultdict处理字典默认值
my_dict = defaultdict(int)  # 默认值为0的字典
my_dict['key1'] += 1
print(my_dict['key2'])  # 默认为0

2. itertools:迭代器工具

itertools模块包含一些用于创建和操作迭代器的函数,如permutations、combinations和cycle。

from itertools import permutations, combinations, cycle

# 使用permutations生成元素的所有排列
perms = permutations([123])
for perm in perms:
    print(perm)

# 使用combinations生成元素的组合
combs = combinations([123], 2)
for comb in combs:
    print(comb)

# 使用cycle创建循环迭代器
my_list = [123]
cycle_iter = cycle(my_list)
for _ in range(5):
    print(next(cycle_iter))

3. functools:函数式编程工具

functools模块提供了一些函数式编程工具,如partial、reduce和lru_cache。

from functools import partial, reduce, lru_cache

# 使用partial创建函数副本
def power(x, exponent):
    return x ** exponent

square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(4))  # 16
print(cube(4))  # 64

# 使用reduce进行累积操作
numbers = [1234]
result = reduce(lambda x, y: x * y, numbers)
print(result)  # 24

# 使用lru_cache进行函数结果缓存
@lru_cache(maxsize=None)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

4. gzip 和 bz2:压缩和解压缩

gzip和bz2模块允许您进行文件的压缩和解压缩操作,这在处理大型数据文件时非常有用。

import gzip
import bz2

# 压缩文件
with open('data.txt''rb'as f_in, gzip.open('data.txt.gz''wb'as f_out:
    f_out.writelines(f_in)

# 解压缩文件
with gzip.open('data.txt.gz''rb'as f_in, open('data_restored.txt''wb'as f_out:
    f_out.writelines(f_in)

# 使用bz2进行类似的操作

5. json:处理JSON数据

json模块用于解析和生成JSON数据,这在处理Web服务响应和配置文件时非常常见。

import json

# 将Python对象转换为JSON字符串
data = {"name""John""age"30}
json_str = json.dumps(data)

# 将JSON字符串解析为Python对象
json_data = json.loads(json_str)

6. calendar 和 datetime:日期和时间处理

calendar和datetime模块用于处理日期和时间,包括日期计算和格式化。

import calendar
from datetime import datetime

# 获取当前日期和时间
now = datetime.now()
print(now)

# 获取日历
cal = calendar.month(20239)
print(cal)

7. sqlite3:内置的SQLite数据库接口

sqlite3模块是Python内置的SQLite数据库接口,允许您轻松创建和管理SQLite数据库。

import sqlite3

# 连接到数据库(如果不存在则创建)
conn = sqlite3.connect('my_database.db')

# 创建游标对象
cursor = conn.cursor()

# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS books
                  (id INTEGER PRIMARY KEY,
                   title TEXT,
                   author TEXT,
                   year INTEGER)''')

# 插入数据
cursor.execute("INSERT INTO books (title, author, year) VALUES (?, ?, ?)", ("Example Book""John Doe"2023))

# 提交更改
conn.commit()

# 查询数据
cursor.execute("SELECT * FROM books")
for row in cursor.fetchall():
    print(row)

# 关闭连接
conn.close()

8. collections.abc:抽象基类

collections.abc模块定义了一些抽象基类,如Iterable和Mapping,可用于自定义类以实现迭代和映射接口。

from collections.abc import Iterable, Mapping

# 自定义可迭代对象
class MyIterable:
    def __init__(self):
        self.data = [123]
    
    def __iter__(self):
        return iter(self.data)

my_iterable = MyIterable()
print(isinstance(my_iterable, Iterable))  # True

# 自定义映射对象
class MyMapping:
    def __init__(self):
        self.data = {"a"1"b"2}
    
    def __getitem__(self, key):
        return self.data[key]
    
    def __iter__(self):
        return iter(self.data)

my_mapping = MyMapping()
print(isinstance(my_mapping, Mapping))  # True

9. xml.etree.ElementTree:处理XML数据

xml.etree.ElementTree模块用于解析和生成XML数据,可用于处理XML配置文件和Web服务响应。

import xml.etree.ElementTree as ET

# 解析XML文件
tree = ET.parse('data.xml')
root = tree.getroot()

# 遍历XML元素
for elem in root:
    print(elem.tag, elem.text)

# 创建XML元素
new_elem = ET.Element('new_element')
new_elem.text = 'New Element Content'
root.append(new_elem)

# 生成XML文件
tree.write('new_data.xml')

这些鲜为人知但非常实用的Python标准库模块可在多种编程场景中派上用场。

掌握这些鲜为人知的标准库模块可以让你更高效地编写Python代码,提升开发效率。

更多学习资料:

长按扫码发送:「优质资料」

Python中9个鲜为人知的宝藏标准库

长按发送「优质资料

喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址