你可能不知道的实用 Python 功能(python有哪些用)
off999 2025-06-15 18:36 31 浏览 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}")。
相关推荐
- 电脑c盘格式化了怎么装系统(电脑c盘格式化后还能用吗)
-
C盘只有格式化才能中心装系统吗?不是的。C盘格式化是为了让C盘更清洁,这样装了的系统比较纯净的。没有系统来及,用起来更是的速度快。格式化(format)是指对磁盘或磁盘中的分区(partition)进...
- 佳能(中国)官网下载(佳能(中国)官网下载appstore)
-
需要先进入佳能官网的下载页面,选择手机APP下载选项,根据手机操作系统的不同选择相应的下载链接即可成功下载佳能手机APP。下载链接通常会在网站的首页或者是产品页面上提供。总的来说,下载佳能手机APP非...
- c盘右边有个恢复分区怎么删除
-
1、从网上下载“分区助手专业6.2(或5.6)”,它能无损分区,下载后打开按提示安装,点击分区助手桌面快捷方式图标,打开分区助手专业版6.2主界面。2、右击要调出空间的分区,如E,选“分配自由空间”,...
- 电脑插着电源却不充电怎么办
-
电脑插上电源但无法充电可能有以下原因:1.电池没有完全安装,需要检查电池是否完全插入笔记本电脑中。2.电池损坏,如果电池老化或发生机械故障、磨损和损伤,充电电流将会被阻塞从而无法进行充电,需要更换...
-
- 如何格式化手机(华为p50如何格式化手机)
-
步骤/方式1软件格式化:利用psiloc公司的软件sTools,进行格式化手机,锁码为12345步骤/方式2软格:在手机上输入*#7370#之后要求你输入锁码,初始密码是:12345步骤/方式3硬格:先关机,再开机的时候按住拨号键、“*...
-
2025-12-17 12:03 off999
- win10自动更新的禁用方法(win10自动更新的禁用方法是什么)
-
方法一:Windows设置 要想关闭Win10自动更新,比较简单的一种方法就是进入到Windows设置中,将Windows更新直接关闭。步骤如下: 1、按“Windows+I”键,打开Wind...
- 优化win7系统运行速度(优化win7系统运行速度多少)
-
优化WIN7系统开机启动项的操作方法1、在桌面上按组合键(win键+R)打开运行窗口,接着输入“regedit”,回车确认,2、打开注册表编辑器后,我们依次点击展开“HKEY_CURRENT_USE...
- win7设置每天自动开机时间(win7设置每天自动开机时间任务)
-
要在Windows7上设置每天自动开关机,您可以按照以下步骤操作:1.打开“控制面板”,单击“系统和安全”,然后选择“计划任务”。2.单击“创建基本任务”,输入一个适合您的任务名称,并添加相应的...
- 苹果电脑装双系统好用吗(苹果电脑安装双系统会不会对电脑不好)
-
好处:1、可以在保留原来的系统上再安装一个新系统,两个系统互不干扰,可以互相切换,使用方便。2、双系统可以在不用环境系进行软件调试没测试电脑的兼容性。3、双系统可以让用户体验不同的系统功能,提高用户的...
- 在电脑上复制粘贴按什么键(电脑怎复制粘贴按那个键)
-
电脑键盘上的“复制和粘贴”,分别是Ctrl+c和Ctrl+v,其中复制的快捷键是Ctrl+c,粘贴的快捷键是Ctrl+v。鼠标右键,点击右键会出菜单,移动光标后点击左键确认。键盘复制的快捷键:Ctrl...
- office是电脑自带的吗(电脑自带的office都是2016版)
-
基本上大品牌电脑,都会带正版的office软件。如果是自己组装的电脑,一般使用的盗版软件,不是正版的。现在office软件分为国产和进口两个版本,进口的是微软office,国产的是wpsoffice...
欢迎 你 发表评论:
- 一周热门
-
-
抖音上好看的小姐姐,Python给你都下载了
-
全网最简单易懂!495页Python漫画教程,高清PDF版免费下载
-
Python 3.14 的 UUIDv6/v7/v8 上新,别再用 uuid4 () 啦!
-
飞牛NAS部署TVGate Docker项目,实现内网一键转发、代理、jx
-
python入门到脱坑 输入与输出—str()函数
-
宝塔面板如何添加免费waf防火墙?(宝塔面板开启https)
-
Python三目运算基础与进阶_python三目运算符判断三个变量
-
(新版)Python 分布式爬虫与 JS 逆向进阶实战吾爱分享
-
失业程序员复习python笔记——条件与循环
-
使用 python-fire 快速构建 CLI_如何搭建python项目架构
-
- 最近发表
- 标签列表
-
- 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)
