掌握这些Python技巧,新手也能写出专业级代码
Python以其简洁优雅的语法和强大的功能库成为最受欢迎的编程语言之一。本文将分享40个实用Python技巧,涵盖基础操作、数据处理、函数使用和高效编程等方面,每个技巧都配有详细代码示例和解读,助你快速提升Python编程能力!
一、基础操作技巧
1. 一行代码交换变量值
a, b = 10, 20
a, b = b, a # 优雅交换
print(a, b) # 输出:20 10
2. 链式比较
x = 15
print(10 < x < 20) # 输出:True
3. 合并字典(Python 3.9+)
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = dict1 | dict2 # 使用管道符合并
print(merged) # {'a':1, 'b':3, 'c':4}
4. 列表元素快速去重
nums = [1, 2, 2, 3, 4, 4, 5]
unique = list(set(nums))
print(unique) # [1, 2, 3, 4, 5]
二、数据处理技巧
5. 列表推导式高效创建
# 创建0-9的平方列表
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
6. 字典推导式
# 快速创建字符ASCII码字典
ascii_dict = {char: ord(char) for char in 'abcde'}
print(ascii_dict) # {'a':97, 'b':98, 'c':99, 'd':100, 'e':101}
7. 使用zip同时遍历多个列表
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
8. 高级切片技巧
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[::2]) # 奇数位元素 [1, 3, 5, 7, 9]
print(nums[::-1]) # 列表反转 [9, 8, 7, 6, 5, 4, 3, 2, 1]
三、函数使用技巧
9. 函数参数解包
def connect(host, port, timeout=10):
print(f"Connecting to {host}:{port}, timeout={timeout}")
params = {'host': 'example.com', 'port': 443, 'timeout': 5}
connect(**params) # 字典解包传参
10. 使用lambda创建匿名函数
# 对列表按字符串长度排序
words = ['banana', 'pie', 'Washington', 'book']
words.sort(key=lambda x: len(x))
print(words) # ['pie', 'book', 'banana', 'Washington']
11. 使用functools.partial冻结参数
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2) # 固定指数为2
print(square(5)) # 25
四、高效编程技巧
12. 使用enumerate获取索引
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
13. 使用collections.Counter计数
from collections import Counter
text = "python is powerful and python is easy"
word_count = Counter(text.split())
print(word_count.most_common(2)) # [('python',2), ('is',2)]
14. 使用itertools高效迭代
import itertools
# 生成所有可能的两位字母组合
combinations = list(itertools.product('AB', repeat=2))
print(combinations) # [('A','A'), ('A','B'), ('B','A'), ('B','B')]
15. 使用生成器节省内存
def large_range(n):
"""生成0到n-1的数字,节省内存"""
i = 0
while i < n:
yield i
i += 1
# 使用生成器代替列表
for num in large_range(1000000):
if num % 100000 == 0:
print(num)
五、文件与异常处理
16. 使用with自动管理资源
with open('data.txt', 'r') as file:
content = file.read()
print(content[:100]) # 打印前100个字符
# 文件会在with块结束后自动关闭
17. 异常处理完整结构
try:
result = 10 / int(input("输入除数: "))
except ValueError:
print("请输入数字!")
except ZeroDivisionError:
print("除数不能为0!")
else:
print(f"结果是: {result}")
finally:
print("计算完成")
六、高效调试技巧
18. 使用__slots__节省内存
class Player:
__slots__ = ['name', 'score'] # 限制属性
def __init__(self, name, score):
self.name = name
self.score = score
# 比普通类节省40%-50%内存
19. 使用timeit测试代码性能
import timeit
# 比较两种创建列表方式的性能
list_time = timeit.timeit('[x**2 for x in range(1000)]', number=1000)
map_time = timeit.timeit('list(map(lambda x: x**2, range(1000)))', number=1000)
print(f"列表推导式: {list_time:.5f}s, map函数: {map_time:.5f}s")
七、面向对象高级技巧
20. 使用dataclass简化类
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
z: float = 0.0 # 默认值
p = Point(1.5, 2.5)
print(p) # Point(x=1.5, y=2.5, z=0.0)
结语
本文涵盖的20个Python技巧从基础到高级层层递进,每个技巧都经过实战检验。掌握这些技巧,你不仅能写出更简洁高效的代码,还能解决实际开发中的复杂问题。建议收藏本文,并在日常编码中实践这些技巧,你的Python水平必将突飞猛进!
你最喜欢哪个技巧?或者有更好的技巧分享?欢迎在评论区留言讨论!关注我,获取更多Python干货内容。