你可能不知道的实用 Python 功能(python有哪些用)
off999 2025-06-15 18:36 38 浏览 0 评论
1. 超越文件处理的内容管理器
大多数开发人员都熟悉使用 with 语句进行文件操作:
with open('file.txt', 'r') as file:
content = file.read()
# File is automatically closed after this block但是, 内容管理器 可以做更多更多。它们是所有类型资源管理的完美选择:
from contextlib import contextmanager
import time
@contextmanager
def timer():
"""Measure execution time of a code block."""
start = time.time()
try:
yield # This is where the code within the 'with' block executes
finally:
end = time.time()
print(f"Elapsed time: {end - start:.4f} seconds")
# Usage
with timer():
# Some time-consuming operation
result = sum(range(10_000_000))contextlib 模块还提供了方便的工具,比如 suppress 用于抑制特定的异常 :
from contextlib import suppress
# Instead of:
try:
os.remove('temp_file.txt')
except FileNotFoundError:
pass
# You can write:
with suppress(FileNotFoundError):
os.remove('temp_file.txt')2. 部分函数
functools.partial (?) 函数允许你创建带有预填充参数的新函数 :
from functools import partial
# Instead of writing a new function
def power_of_two(x):
return pow(x, 2)
# You can use partial
power_of_two = partial(pow, exp=2)
# Create a base-2 logarithm function
import math
log2 = partial(math.log, base=2)
print(log2(8)) # Outputs: 3.0这对于回调函数或在处理 高阶函数 时特别有用。
3. 解构泛化
解包运算符 * 和 ** 比我们大多数人都意识到的要更通用:
# Merging dictionaries (Python 3.5+)
defaults = {"colour": "red", "size": "medium"}
user_settings = {"size": "large", "mode": "advanced"}
settings = {**defaults, **user_settings}
print(settings) # {'colour': 'red', 'size': 'large', 'mode': 'advanced'}
# Extended unpacking (Python 3.0+)
first, *middle, last = [1, 2, 3, 4, 5]
print(middle) # [2, 3, 4]
# Unpacking in function calls
def tag(name, **attributes):
attr_str = ' '.join(f'{k}="{v}"' for k, v in attributes.items())
return f'<{name} {attr_str}>'
props = {"class": "button", "id": "submit-btn", "disabled": True}
print(tag("button", **props)) # <button class="button" id="submit-btn" disabled="True">4. 省略号(...)的意外用途
省略号字面量不只是用于类型提示:
# As a placeholder for future code
def function_to_implement_later():
... # More explicit than 'pass'
# In multidimensional NumPy slicing
import numpy as np
array = np.random.rand(4, 4, 4)
# Select the middle column from all rows in all matrices
middle_column = array[:, 1, ...]5. 函数属性
Python 函数是对象,可以有属性 :
def process_data(data, verbose=False):
"""Process the given data."""
if verbose or process_data.always_verbose:
print("Processing data...")
# Processing logic here
return data
# Add an attribute to the function
process_data.always_verbose = False
# Later in your code
process_data.always_verbose = True # Enable verbose mode globally这可以是在某些情况下作为全局变量的一个酷替代方案。
6. 自定义排序键使用key=参数
排序函数中的 key 参数比大多数人意识到的要强大得多:
# Sort strings by length
words = ["apple", "pear", "banana", "strawberry", "fig"]
sorted_by_length = sorted(words, key=len)
print(sorted_by_length) # ['fig', 'pear', 'apple', 'banana', 'strawberry']
# Sort complex objects
from operator import attrgetter, itemgetter
# For a list of dictionaries
users = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35}
]
sorted_users = sorted(users, key=itemgetter("age"))
# For a list of objects
from collections import namedtuple
Person = namedtuple("Person", ["name", "age"])
people = [Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35)]
sorted_people = sorted(people, key=attrgetter("age"))7. 默认字典和计数器集合
collections 模块包含可以替代常见模式的数据结构 :
from collections import defaultdict, Counter
# Instead of:
word_count = {}
for word in text.split():
if word not in word_count:
word_count[word] = 0
word_count[word] += 1
# You can use:
word_count = defaultdict(int)
for word in text.split():
word_count[word] += 1
# Or even simpler:
word_count = Counter(text.split())
print(word_count.most_common(5)) # Shows the 5 most common words8. 枚举类型用于更好的常量
枚举模块有助于定义有意义的常量:
from enum import Enum, auto
class Status(Enum):
PENDING = auto()
RUNNING = auto()
COMPLETED = auto()
FAILED = auto()
def process_job(job, status):
if status == Status.RUNNING:
print(f"Job {job} is still running")
elif status == Status.COMPLETED:
print(f"Job {job} completed successfully")
# ...
# So much more readable than numeric constants
current_status = Status.RUNNING
process_job("backup", current_status)9. 数据类用于更简洁的代码
Python 3.7 引入了 数据类 (通过 PEP-557),它们减少了主要用于存储数据的类中的样板代码:
from dataclasses import dataclass, field
from typing import List
@dataclass
class Student:
name: str
student_id: int
courses: List[str] = field(default_factory=list)
active: bool = True
def enroll(self, course):
self.courses.append(course)
# No need to write __init__, __repr__, __eq__, etc.
student = Student("Jane Smith", 12345)
student.enroll("Computer Science 101")
print(student) # Student(name='Jane Smith', student_id=12345, courses=['Computer Science 101'], active=True)10. 使用__slots__提高内存效率
对于具有固定属性集的类,__slots__ 可以显著减少内存使用:
class RegularPoint:
def __init__(self, x, y):
self.x = x
self.y = y
class MemoryEfficientPoint:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
# The __slots__ version uses significantly less memory when many instances are created
import sys
regular = RegularPoint(3, 4)
efficient = MemoryEfficientPoint(3, 4)
print(sys.getsizeof(regular)) # Typically larger
print(sys.getsizeof(efficient)) # Typically smaller11. f 字符串调试(Python 3.8+)
在 Python 3.8 中,f 字符串增加了一个方便的调试功能: 已添加
x = 10
y = 20
print(f"{x=}, {y=}, {x+y=}")
# Outputs: x=10, y=20, x+y=30通过显示变量名及其值,在调试时节省时间。
12. pathlib 用于现代文件操作
pathlib 模块为文件系统路径提供了面向对象的方法:
from pathlib import Path
# Create paths
data_dir = Path("data")
file_path = data_dir / "output.txt" # Path joining with / operator
# Create directory if it doesn't exist
data_dir.mkdir(exist_ok=True)
# Write to a file
file_path.write_text("Hello, world!")
# Read from a file
content = file_path.read_text()
# Iterate over files in a directory
for python_file in data_dir.glob("*.py"):
print(f"Found Python file: {python_file.name}")。
相关推荐
- 祖玛传奇手机版下载(祖玛传奇手机版下载赚红包)
-
1.可能是因为下载链接失效或者被删除了。2.经典祖玛传奇是一款非常受欢迎的游戏,可能存在版权问题或者侵权问题,导致下载链接被删除或者失效。3.如果想要玩经典祖玛传奇,可以尝试在正规的游戏平台或者...
- 免费音乐剪辑软件(免费音乐编辑软件)
-
AdobeAudition(Windows系统和Mac系统都可以)和CoolEditPro(Windows系统)!这两款软件都是免费的,音频剪辑方面功能很全。例如:分音轨、多音轨混录、降噪、立体...
- sdwan跨境专线(sdwan跨境专线个人能申请么)
-
SD-WAN跨境专线在合规合法方面存在一些具体的限制。在不同国家和地区的法律法规布局上存在差异,因此,跨境专线一定要遵守所在国家和地区的相关规定,例如中国的《关于规范互联网接入服务市场秩序的若干规定》...
- 北京科兴疫苗(北京科兴疫苗对人体的影响)
-
合格。国家有各种疫苗的审核标准,达到标准后才可以接种。国家不可能让不合格的疫苗,进入接种环节。这点大家可以放心!近期可能都不会有科兴的疫苗,是因为国家购入数量较少的原因。因为科兴是由北京科兴生物制品有...
- 阿里旺旺官网入口(阿里旺旺app官网)
-
阿里巴巴国际站旺旺有手机版。国际版阿里旺旺的下载地址是:http://trademanager.alibaba.com/有IOS和android版本阿里巴巴国际站是阿里巴巴集团最早创立的业务,是目前...
- google地球手机版下载(google地球7.12手机版)
-
手机版本的还是电脑版本的呀,电脑版本的直接在谷歌的网站下载就是了,手机版本的就是在谷歌play商店下载就是了。需要告诉你的是,国内无法使用谷歌地球。可以在应用宝中下载,然后将下载好的谷歌地球导入进Ou...
-
- windows11云电脑(在线windows云电脑)
-
关闭win11的云端服务的方法如下1.首先我们进入手机设置,然后点击我们的用户名称可以进入账号设置。2.确认信息后,点击“退出账号”即可关闭华为云空间了,如果我们只想要关闭备份功能的话,可以进入“云空间”3.接着点击其中的云备份选项进入,最...
-
2026-02-01 13:15 off999
- 诺基亚所有型号及图片(诺基亚所有型号及图片及价格)
-
诺基亚:N71、N73、N75、N76、N77、N78、N79、N80、N81、N81(8GB)、N82、N85、N91、N91(8GB)、N92、N93、N93i、N95、N95(8GB)、N96、...
- 星空视频壁纸(星空壁纸引擎)
-
星空视频壁纸设置方法:打开“开始”→“控制面板”→“更改桌面背景”→有个关于图片属性的,选择“填充”即可,还可以从“计算机”-----“组织”----“属性”----“控制面板”,其余重复一样的。您...
- 图片文字识别软件(图片文字识别软件哪个好)
-
华为手机自带文件扫描,打开华为手机的相机,选择左上角的那个图标,点进去之后下面会看到一个文字的图标,选择那个就可以对准文件拍照自动识别了,自己手写的也可以识别,就是精准度会根据你写的字的工整程度有影响...
- 新盟网上订烟草登录(新盟手机网上订烟草登录)
-
找你所在的管辖区域客户经理申请帐号,他会给你的。新商盟用户名是零售户的客户编码,送烟小票上有,不清楚的可以致电客户经理。初始密码是零售户开通新商盟的时候电脑系统随即分配的六位数。根据你说的情况,分析情...
- 电信网上营业厅入口(电信网上营业大厅)
-
你好,查询各地营业厅号码,只需拨打114号码百事通即可。要找到电信的营业厅,可以通过多种途径进行查询。首先,可以在电信官方网站上查找最近的营业厅地址和联系方式。其次,可以通过拨打电信客服热线100查询...
- 期货公司哪家手续费最便宜(正规的期货公司哪家手续费低)
-
华泰长城期货公司开户手续费是业内比较低的,股指开户手续费万0.275,商品期货开户在交易所基础加收30%。反正是没有手续费最低的期货公司,手续费高低是期货公司适度调节的,只要客户的成交量大,期货公司就...
- txt免费全本小说阅读器下载安装
-
将小说转换成TXT形式有多种方法,以下是两种常见的方法:方法一:使用在线转换工具打开电脑浏览器,搜索并找到一个可靠的在线电子书转换工具,如“转转大师”。在工具网站上,选择“电子书转换”功能,并点击“电...
- 最好听的十大铃音(铃声歌曲大全免费听)
-
1、《花海》-周杰伦2、《gorgeous》-霉霉3、《水星记》-郭顶4、《樱花樱花想见你》-RSP5、《小幽默》-阿坤6、《有暖气》-橘子海7、《约定》-陈奕迅8、《春风吹》-方大同9、《landi...
欢迎 你 发表评论:
- 一周热门
-
-
抖音上好看的小姐姐,Python给你都下载了
-
全网最简单易懂!495页Python漫画教程,高清PDF版免费下载
-
飞牛NAS部署TVGate Docker项目,实现内网一键转发、代理、jx
-
win7系统还原步骤图解(win7还原电脑系统的步骤)
-
Python 3.14 的 UUIDv6/v7/v8 上新,别再用 uuid4 () 啦!
-
python入门到脱坑 输入与输出—str()函数
-
16949认证费用是多少(16949审核员太难考了)
-
linux软件(linux软件图标)
-
Python三目运算基础与进阶_python三目运算符判断三个变量
-
(新版)Python 分布式爬虫与 JS 逆向进阶实战吾爱分享
-
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)
