Python速查表旨在为开发者提供核心语法、常用函数和关键概念的快速参考,尤其适合日常编码时查阅。以下内容整合了基础语法、数据结构、函数、模块、面向对象编程以及高级特性,并附有代码示例。
### **1. 基础语法与数据类型**
Python 使用缩进(通常是 4 个空格)来定义代码块,而非大括号 [ref_4]。
#### **1.1 变量与基本数据类型**
Python 是动态类型语言,变量无需声明类型 [ref_6]。
```python
# 变量赋值
x = 10 # 整数 (int)
y = 3.14 # 浮点数 (float)
name = "Alice" # 字符串 (str)
is_valid = True # 布尔值 (bool)
```
#### **1.2 数字与运算符**
```python
# 算术运算符
a = 10 + 3 # 13
b = 10 - 3 # 7
c = 10 * 3 # 30
d = 10 / 3 # 3.333... (浮点除)
e = 10 // 3 # 3 (整除)
f = 10 % 3 # 1 (取模)
g = 10 ** 3 # 1000 (幂运算)
# 比较运算符
print(10 > 3) # True
print(10 == 3) # False
print(10 != 3) # True
# 逻辑运算符
print(True and False) # False
print(True or False) # True
print(not True) # False
```
### **2. 数据结构**
Python 内置了多种强大的数据结构 [ref_3]。
#### **2.1 序列类型:列表、元组、字符串**
| 类型 | 描述 | 可变性 | 示例 |
| :--- | :--- | :--- | :--- |
| **列表 (List)** | 有序集合,元素可重复 | 可变 | `my_list = [1, 2, 'a']` |
| **元组 (Tuple)** | 有序集合,元素可重复 | **不可变** | `my_tuple = (1, 2, 'a')` |
| **字符串 (String)** | 字符序列 | **不可变** | `my_str = "hello"` |
**列表常用操作:**
```python
# 创建与访问
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # 1 (正向索引)
print(my_list[-1]) # 5 (负向索引)
# 切片操作 [start:end:step]
print(my_list[1:4]) # [2, 3, 4]
print(my_list[::-1]) # [5, 4, 3, 2, 1] (反转)
# 修改列表
my_list.append(6) # 末尾添加元素
my_list.insert(0, 0) # 在索引0处插入0
my_list.remove(3) # 删除第一个值为3的元素
popped = my_list.pop() # 移除并返回最后一个元素
# 列表推导式 (List Comprehension) [ref_4]
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
```
**字符串常用操作:**
```python
s = "Hello, World!"
print(s.upper()) # "HELLO, WORLD!"
print(s.lower()) # "hello, world!"
print(s.split(",")) # ['Hello', ' World!']
print(",".join(["A", "B", "C"])) # "A,B,C"
print(f"Value: {x}") # f-string 格式化 (Python 3.6+) [ref_4]
```
#### **2.2 映射类型:字典 (Dictionary)**
字典是键值对的无序集合,键必须是不可变类型(如字符串、数字、元组)[ref_3]。
```python
# 创建字典
my_dict = {"name": "Alice", "age": 30}
# 访问与修改
print(my_dict["name"]) # "Alice"
my_dict["age"] = 31 # 修改值
my_dict["city"] = "NYC" # 添加新键值对
# 常用方法
keys = my_dict.keys() # 获取所有键
values = my_dict.values() # 获取所有值
items = my_dict.items() # 获取所有键值对
# 字典推导式
squared = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
```
#### **2.3 集合 (Set)**
集合是无序且元素唯一的容器。
```python
my_set = {1, 2, 3, 3} # {1, 2, 3} (自动去重)
my_set.add(4)
my_set.remove(2)
# 集合运算
set_a = {1, 2, 3}
set_b = {3, 4, 5}
print(set_a | set_b) # 并集: {1, 2, 3, 4, 5}
print(set_a & set_b) # 交集: {3}
print(set_a - set_b) # 差集: {1, 2}
```
### **3. 流程控制**
#### **3.1 条件判断 (if/elif/else)**
```python
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B' # 此分支将被执行
else:
grade = 'C'
print(grade) # 输出: B
```
#### **3.2 循环 (for/while)**
```python
# for 循环遍历序列
for i in range(5): # range(5) 生成 0,1,2,3,4
print(i)
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# while 循环
count = 0
while count < 3:
print(count)
count += 1
# 循环控制
for i in range(10):
if i == 3:
continue # 跳过本次循环剩余代码
if i == 7:
break # 完全终止循环
print(i)
```
### **4. 函数**
函数使用 `def` 关键字定义 [ref_4]。
#### **4.1 函数定义与调用**
```python
def greet(name, greeting="Hello"): # greeting 是默认参数
"""这是一个简单的问候函数。""" # 文档字符串
return f"{greeting}, {name}!"
result = greet("Alice") # 使用默认参数
print(result) # 输出: Hello, Alice!
result2 = greet("Bob", "Hi") # 传递参数
print(result2) # 输出: Hi, Bob!
```
#### **4.2 参数类型**
| 参数类型 | 语法 | 描述 |
| :--- | :--- | :--- |
| **位置参数** | `func(a, b)` | 按顺序传递 |
| **关键字参数** | `func(a=1, b=2)` | 按参数名传递,顺序无关 |
| **默认参数** | `def func(a=1)` | 定义时指定默认值 |
| **可变位置参数** | `def func(*args)` | 接收任意数量的位置参数,打包为元组 |
| **可变关键字参数** | `def func(**kwargs)` | 接收任意数量的关键字参数,打包为字典 |
```python
def flexible_func(a, b=10, *args, **kwargs):
print(f"a={a}, b={b}")
print(f"args: {args}") # 额外的位置参数元组
print(f"kwargs: {kwargs}") # 额外的关键字参数字典
flexible_func(1, 2, 3, 4, 5, key1='value1', key2='value2')
# 输出:
# a=1, b=2
# args: (3, 4, 5)
# kwargs: {'key1': 'value1', 'key2': 'value2'}
```
#### **4.3 Lambda 表达式**
用于创建匿名函数,适合简单的单行函数 [ref_4]。
```python
add = lambda x, y: x + y
print(add(5, 3)) # 8
# 常用于 sorted、map、filter 等函数
nums = [1, 4, 2, 3]
sorted_nums = sorted(nums, key=lambda x: -x) # 按降序排序
print(sorted_nums) # [4, 3, 2, 1]
```
### **5. 模块与包**
模块是一个 `.py` 文件,包是一个包含 `__init__.py` 文件的目录 [ref_6]。
#### **5.1 导入模块**
```python
# 导入整个模块
import math
print(math.sqrt(16)) # 4.0
# 导入特定函数/变量
from math import pi, sin
print(sin(pi/2)) # 1.0
# 使用别名
import numpy as np
import pandas as pd
```
#### **5.2 创建与使用自定义模块**
假设有文件 `mymodule.py`:
```python
# mymodule.py
def my_function():
return "Hello from my module!"
```
在另一个文件中使用:
```python
import mymodule
print(mymodule.my_function()) # "Hello from my module!"
```
### **6. 面向对象编程 (OOP)**
#### **6.1 类与对象**
```python
class Dog:
# 类属性 (所有实例共享)
species = "Canis familiaris"
# 构造方法,初始化实例属性
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
# 实例方法
def bark(self):
return f"{self.name} says woof!"
# 特殊方法 (魔术方法)
def __str__(self):
return f"{self.name} is {self.age} years old."
# 创建对象 (实例化)
my_dog = Dog("Buddy", 5)
print(my_dog.bark()) # 调用方法
print(my_dog) # 调用 __str__ 方法
print(my_dog.species) # 访问类属性
```
#### **6.2 继承**
```python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal): # 继承自 Animal
def speak(self): # 重写父类方法
return f"{self.name} says meow!"
my_cat = Cat("Whiskers")
print(my_cat.speak()) # "Whiskers says meow!"
```
### **7. 异常处理**
使用 `try...except...finally` 来捕获和处理异常 [ref_4]。
```python
try:
num = int(input("请输入一个数字: "))
result = 10 / num
print(f"结果是: {result}")
except ValueError:
print("错误:输入的不是有效数字!")
except ZeroDivisionError:
print("错误:不能除以零!")
except Exception as e: # 捕获所有其他异常
print(f"发生未知错误: {e}")
else:
print("计算成功完成!") # 仅在无异常时执行
finally:
print("程序执行结束。") # 无论是否发生异常都会执行
```
### **8. 文件操作**
#### **8.1 基本文件读写**
```python
# 写入文件
with open('example.txt', 'w', encoding='utf-8') as f: # 使用 with 自动关闭文件
f.write("Hello, World!\n")
f.write("This is a second line.")
# 读取文件
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read() # 读取全部内容
# content = f.readline() # 读取一行
# lines = f.readlines() # 读取所有行,返回列表
print(content)
```
#### **8.2 上下文管理器 (with 语句)**
`with` 语句确保资源(如文件)在使用后被正确关闭,即使发生异常也是如此 [ref_4]。
### **9. 常用内置函数与标准库模块**
#### **9.1 常用内置函数**
| 函数 | 描述 | 示例 |
| :--- | :--- | :--- |
| `len()` | 返回对象长度 | `len([1,2,3])` → `3` |
| `type()` | 返回对象类型 | `type(10)` → `<class 'int'>` |
| `isinstance()` | 检查对象是否为指定类型 | `isinstance(10, int)` → `True` |
| `range()` | 生成整数序列 | `list(range(3))` → `[0, 1, 2]` |
| `enumerate()` | 返回索引和值的枚举 | `list(enumerate(['a','b']))` → `[(0,'a'), (1,'b')]` |
| `zip()` | 将多个序列组合成元组 | `list(zip([1,2], ['a','b']))` → `[(1,'a'), (2,'b')]` |
| `map()` | 对序列每个元素应用函数 | `list(map(str, [1,2,3]))` → `['1','2','3']` |
| `filter()` | 过滤序列中符合条件的元素 | `list(filter(lambda x: x>0, [-1,0,1]))` → `[1]` |
| `sorted()` | 返回排序后的新列表 | `sorted([3,1,2])` → `[1,2,3]` |
#### **9.2 常用标准库模块**
* **`os`**: 操作系统交互,如文件路径操作。
* **`sys`**: 访问解释器相关变量和函数。
* **`datetime`**: 日期和时间处理。
* **`json`**: JSON 数据的编码和解码。
* **`re`**: 正则表达式操作。
* **`math` / `cmath`**: 数学运算。
* **`random`**: 生成随机数。
* **`collections`**: 提供额外的高效数据结构,如 `defaultdict`, `Counter`。
```python
import json
# 将 Python 对象转换为 JSON 字符串
data = {"name": "Alice", "age": 30}
json_str = json.dumps(data)
print(json_str) # '{"name": "Alice", "age": 30}'
# 将 JSON 字符串解析为 Python 对象
parsed_data = json.loads(json_str)
print(parsed_data["name"]) # Alice
```
### **10. 高级特性与技巧**
#### **10.1 装饰器 (Decorator)**
装饰器是修改或增强函数行为的函数,使用 `@` 语法 [ref_4]。
```python
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# 输出:
# Something is happening before the function is called.
# Hello!
# Something is happening after the function is called.
```
#### **10.2 生成器 (Generator)**
生成器使用 `yield` 关键字,可以惰性生成值,节省内存 [ref_5]。
```python
def count_up_to(max):
count = 1
while count <= max:
yield count # 每次 yield 产生一个值,并暂停
count += 1
counter = count_up_to(3)
print(next(counter)) # 1
print(next(counter)) # 2
print(next(counter)) # 3
# print(next(counter)) # 再次调用会引发 StopIteration 异常
# 通常用 for 循环迭代
for num in count_up_to(5):
print(num) # 依次打印 1,2,3,4,5
```
#### **10.3 类型提示 (Type Hints)**
Python 3.5+ 支持类型提示,提高代码可读性和可维护性 [ref_5]。
```python
from typing import List, Dict, Optional
def greet_all(names: List[str]) -> Dict[str, str]:
"""接受一个字符串列表,返回一个问候字典。"""
greetings = {}
for name in names:
greetings[name] = f"Hello, {name}!"
return greetings
result: Dict[str, str] = greet_all(["Alice", "Bob"])
print(result) # {'Alice': 'Hello, Alice!', 'Bob': 'Hello, Bob!'}
```
此速查表涵盖了 Python 编程的核心知识,从基础语法到高级特性,可作为日常开发的快速参考。掌握这些内容能有效提升编码效率和代码质量 [ref_2][ref_3][ref_4][ref_5][ref_6]。