Files
personal-blog-20260928164707/posts/python-tips.md
T

49 lines
862 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: 5 个实用的 Python 小技巧
date: 2024-02-20
summary: 分享几个日常开发中非常实用的 Python 技巧,让你的代码更简洁。
---
## 1. 使用 enumerate 获取索引
```python
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
print(i, fruit)
```
## 2. 列表推导式
用一行代码完成过滤和映射:
```python
squares = [x * x for x in range(10) if x % 2 == 0]
```
## 3. 使用 zip 同时遍历
```python
names = ['Alice', 'Bob']
ages = [25, 30]
for name, age in zip(names, ages):
print(f'{name} is {age}')
```
## 4. 字典的 get 方法
避免 KeyError:
```python
config = {'debug': True}
level = config.get('level', 'INFO')
```
## 5. 使用 f-string 格式化
```python
name = 'World'
print(f'Hello, {name}!')
```
这些小技巧虽然简单,但能让代码更 Pythonic。