862 B
862 B
title, date, summary
| title | date | summary |
|---|---|---|
| 5 个实用的 Python 小技巧 | 2024-02-20 | 分享几个日常开发中非常实用的 Python 技巧,让你的代码更简洁。 |
1. 使用 enumerate 获取索引
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
print(i, fruit)
2. 列表推导式
用一行代码完成过滤和映射:
squares = [x * x for x in range(10) if x % 2 == 0]
3. 使用 zip 同时遍历
names = ['Alice', 'Bob']
ages = [25, 30]
for name, age in zip(names, ages):
print(f'{name} is {age}')
4. 字典的 get 方法
避免 KeyError:
config = {'debug': True}
level = config.get('level', 'INFO')
5. 使用 f-string 格式化
name = 'World'
print(f'Hello, {name}!')
这些小技巧虽然简单,但能让代码更 Pythonic。