首页 > 应用开发 > IT综合 > Python核心知识点速查:31个必备概念与实用技巧
# Python核心知识点速查:31个必备概念与实用技巧
## 基础语法与变量操作
### 1. 变量命名与赋值
```python
# 变量命名规则
snake_case_variable = "下划线命名法" # Python推荐
camelCaseVariable = "驼峰命名法" # 不常用
CONSTANT_VALUE = 3.14 # 常量全大写
# 多重赋值
a, b, c = 1, 2, 3 # 同时赋值多个变量
x = y = z = 0 # 链式赋值
# 交换变量值
a, b = b, a # Python特有的优雅交换
```
### 2. 数据类型基础
```python
# 基本数据类型
integer_num = 42 # 整数
float_num = 3.14 # 浮点数
complex_num = 2 + 3j # 复数
boolean_val = True # 布尔值
none_val = None # 空值
# 类型检查与转换
print(type(integer_num)) # <class 'int'>
str_num = str(42) # 转换为字符串
int_num = int("123") # 转换为整数
float_num = float("3.14") # 转换为浮点数
```
### 3. 字符串操作
```python
# 字符串创建与格式化
single_quotes = '单引号字符串'
double_quotes = "双引号字符串"
triple_quotes = """多行
字符串"""
# f-string格式化(Python 3.6+)
name = "张三"
age = 25
message = f"姓名:{name},年龄:{age}"
print(message) # 姓名:张三,年龄:25
# 字符串方法
text = " Python 编程 "
trimmed = text.strip() # 去除两端空格
upper_case = text.upper() # 转为大写
split_words = text.split() # 分割字符串
joined = "-".join(["a", "b", "c"]) # 连接字符串
```
### 4. 列表操作
```python
# 列表创建与基本操作
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "文本", True, 3.14]
# 列表索引与切片
first = numbers[0] # 1
last = numbers[-1] # 5
middle = numbers[1:4] # [2, 3, 4]
reversed_list = numbers[::-1] # [5, 4, 3, 2, 1]
# 列表方法
numbers.append(6) # 添加元素
numbers.insert(0, 0) # 插入元素
removed = numbers.pop() # 移除并返回最后一个
numbers.remove(3) # 移除指定元素
numbers.sort() # 排序
numbers.reverse() # 反转
```
### 5. 元组使用
```python
# 元组创建
coordinates = (10, 20)
single_tuple = (42,) # 注意逗号
from_list = tuple([1, 2, 3])
# 元组解包
x, y = coordinates # 解包赋值
a, b, c = (1, 2, 3) # 多重解包
# 不可变特性
# coordinates[0] = 100 # 错误!元组不可修改
```
### 6. 字典操作
```python
# 字典创建
student = {"name": "张三", "age": 20, "major": "计算机"}
empty_dict = {}
from_pairs = dict([("a", 1), ("b", 2)])
# 字典访问与修改
name = student["name"] # 访问值
age = student.get("age") # 安全访问
student["grade"] = "A" # 添加新键值对
student["age"] = 21 # 修改值
# 字典方法
keys = student.keys() # 所有键
values = student.values() # 所有值
items = student.items() # 所有键值对
removed = student.pop("major") # 移除并返回值
```
### 7. 集合运算
```python
# 集合创建
unique_numbers = {1, 2, 3, 4, 5}
from_list = set([1, 2, 2, 3, 3]) # {1, 2, 3}
# 集合运算
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
union_set = set_a | set_b # 并集:{1, 2, 3, 4, 5, 6}
intersection = set_a & set_b # 交集:{3, 4}
difference = set_a - set_b # 差集:{1, 2}
symmetric_diff = set_a ^ set_b # 对称差集:{1, 2, 5, 6}
```
## 流程控制与函数
### 8. 条件语句
```python
# if-elif-else结构
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
print(f"成绩等级: {grade}") # 成绩等级: B
# 条件表达式(三元运算符)
result = "通过" if score >= 60 else "未通过"
print(f"考试结果: {result}")
```
### 9. 循环结构
```python
# for循环
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
print(f"水果: {fruit}")
# 带索引的遍历
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
# while循环
count = 0
while count < 5:
print(f"计数: {count}")
count += 1
# 循环控制
for i in range(10):
if i == 3:
continue # 跳过本次循环
if i == 7:
break # 终止循环
print(i)
```
### 10. 函数定义与调用
```python
# 基本函数
def greet(name, greeting="你好"):
"""返回问候语"""
return f"{greeting}, {name}!"
# 函数调用
message = greet("张三") # 你好, 张三!
custom_greet = greet("李四", "Hello") # Hello, 李四!
# 关键字参数
def create_profile(name, age, city="北京"):
return {"name": name, "age": age, "city": city}
# 可读性更好的调用方式
profile = create_profile(name="王五", age=25, city="上海")
```
### 11. 参数类型
```python
# 可变参数
def sum_numbers(*args):
"""计算任意数量数字的和"""
return sum(args)
total = sum_numbers(1, 2, 3, 4, 5) # 15
# 关键字参数
def print_info(**kwargs):
"""打印键值对信息"""
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="张三", age=25, city="北京")
# 参数组合
def complex_function(a, b, *args, **kwargs):
"""包含所有参数类型的函数"""
print(f"固定参数: {a}, {b}")
print(f"可变参数: {args}")
print(f"关键字参数: {kwargs}")
```
## 高级特性
### 12. 列表推导式
```python
# 基本推导式
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 带条件的推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
# 嵌套推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
```
### 13. 生成器表达式
```python
# 生成器表达式(惰性计算)
squares_gen = (x**2 for x in range(10))
print(list(squares_gen)) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 节省内存的大数据处理
large_data = (x * 2 for x in range(1000000))
for value in large_data:
if value > 100:
break
print(value, end=" ")
```
### 14. lambda函数
```python
# 匿名函数
add = lambda x, y: x + y
result = add(3, 5) # 8
# 在排序中使用
students = [
{"name": "张三", "score": 85},
{"name": "李四", "score": 92},
{"name": "王五", "score": 78}
]
sorted_students = sorted(students, key=lambda s: s["score"], reverse=True)
print(sorted_students)
```
### 15. 装饰器基础
```python
# 简单装饰器
def timer_decorator(func):
"""测量函数执行时间的装饰器"""
def wrapper(*args, **kwargs):
import time
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} 执行时间: {end_time - start_time:.4f}秒")
return result
return wrapper
# 使用装饰器
@timer_decorator
def slow_function():
import time
time.sleep(1)
return "完成"
slow_function()
```
### 16. 异常处理
```python
# try-except结构
try:
result = 10 / 0
number = int("abc")
except ZeroDivisionError:
print("不能除以零")
except ValueError as e:
print(f"值错误: {e}")
except Exception as e:
print(f"未知错误: {e}")
else:
print("没有发生错误")
finally:
print("无论如何都会执行")
# 抛出异常
def validate_age(age):
if age < 0 or age > 150:
raise ValueError("年龄必须在0-150之间")
return age
# 自定义异常
class CustomError(Exception):
"""自定义异常类"""
def __init__(self, message):
super().__init__(message)
self.custom_message = message
```
## 面向对象编程
### 17. 类与对象
```python
# 类定义
class Person:
"""人类"""
# 类属性
species = "人类"
def __init__(self, name, age):
"""初始化方法"""
self.name = name
self.age = age
def introduce(self):
"""自我介绍"""
return f"我叫{self.name},今年{self.age}岁"
@classmethod
def create_baby(cls, name):
"""类方法:创建婴儿"""
return cls(name, 0)
@staticmethod
def is_adult(age):
"""静态方法:判断是否成年"""
return age >= 18
# 创建对象
person1 = Person("张三", 25)
print(person1.introduce())
# 使用类方法
baby = Person.create_baby("李小宝")
print(baby.introduce())
# 使用静态方法
print(Person.is_adult(20)) # True
```
### 18. 继承与多态
```python
# 基类
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("子类必须实现此方法")
# 子类继承
class Dog(Animal):
def speak(self):
return f"{self.name} 说:汪汪!"
class Cat(Animal):
def speak(self):
return f"{self.name} 说:喵喵~"
# 多态演示
animals = [Dog("旺财"), Cat("咪咪")]
for animal in animals:
print(animal.speak())
# 方法重写
class SpecialDog(Dog):
def speak(self):
# 调用父类方法
original_sound = super().speak()
return original_sound + " 我是特别的狗!"
```
### 19. 属性装饰器
```python
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
"""获取半径"""
return self._radius
@radius.setter
def radius(self, value):
"""设置半径(带验证)"""
if value <= 0:
raise ValueError("半径必须为正数")
self._radius = value
@property
def area(self):
"""计算面积(只读属性)"""
return 3.14159 * self._radius ** 2
# 使用属性
circle = Circle(5)
print(f"半径: {circle.radius}, 面积: {circle.area:.2f}")
circle.radius = 10 # 调用setter
print(f"新面积: {circle.area:.2f}")
<"nkl.q6k0.org.cn"><"ikyk.q6k0.org.cn"><"hon.q6k0.org.cn">
```
## 模块与包管理
### 20. 模块导入
```python
# 基本导入
import math
import random
import os.path
# 别名导入
import numpy as np
import pandas as pd
# 选择性导入
from datetime import datetime, timedelta
from collections import defaultdict, Counter
# 导入所有(不推荐)
# from math import *
# 检查模块是否存在
try:
import requests
except ImportError:
print("requests模块未安装")
```
### 21. 创建模块
```python
# mymodule.py 文件内容示例
"""
我的自定义模块
包含一些实用工具函数
"""
def calculate_average(numbers):
"""计算平均值"""
if not numbers:
return 0
return sum(numbers) / len(numbers)
def format_name(first, last):
"""格式化姓名"""
return f"{last}, {first}"
# 模块测试代码
if __name__ == "__main__":
# 模块直接运行时执行的代码
print("模块测试模式")
print(calculate_average([1, 2, 3, 4, 5]))
```
## 文件操作
### 22. 文件读写
```python
# 写入文件
with open("data.txt", "w", encoding="utf-8") as file:
file.write("第一行内容\n")
file.write("第二行内容\n")
# 读取文件
with open("data.txt", "r", encoding="utf-8") as file:
content = file.read() # 读取全部内容
print(content)
# 逐行读取
with open("data.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip()) # 去除换行符
# CSV文件处理
import csv
with open("data.csv", "w", newline="", encoding="utf-8") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["姓名", "年龄", "城市"])
writer.writerow(["张三", 25, "北京"])
writer.writerow(["李四", 30, "上海"])
```
## 标准库实用功能
### 23. collections模块
```python
from collections import Counter, defaultdict, deque
# 计数器
words = ["apple", "banana", "apple", "orange", "banana", "apple"]
word_count = Counter(words)
print(word_count.most_common(2)) # [('apple', 3), ('banana', 2)]
# 默认字典
scores = defaultdict(list)
scores["张三"].append(85)
scores["张三"].append(90)
print(scores["张三"]) # [85, 90]
# 双端队列
queue = deque([1, 2, 3])
queue.append(4) # 右侧添加
queue.appendleft(0) # 左侧添加
item = queue.pop() # 右侧移除
```
### 24. itertools模块
```python
import itertools
# 无限迭代器
counter = itertools.count(start=10, step=2)
next_5 = [next(counter) for _ in range(5)]
print(next_5) # [10, 12, 14, 16, 18]
# 组合与排列
letters = ["A", "B", "C"]
combinations = list(itertools.combinations(letters, 2))
print(combinations) # [('A', 'B'), ('A', 'C'), ('B', 'C')]
permutations = list(itertools.permutations(letters, 2))
print(permutations) # [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
```
## 正则表达式
### 25. 正则匹配
```python
import re
# 基本匹配
text = "联系电话:138-1234-5678"
pattern = r"\d{3}-\d{4}-\d{4}"
match = re.search(pattern, text)
if match:
print(f"找到电话号码: {match.group()}")
# 查找所有匹配
text = "苹果10元,香蕉5元,橙子8元"
prices = re.findall(r"\d+元", text)
print(prices) # ['10元', '5元', '8元']
# 替换
text = "今天是2023-12-15"
new_text = re.sub(r"\d{4}-\d{2}-\d{2}", "某年某月某日", text)
print(new_text) # 今天是某年某月某日
```
## 时间日期处理
### 26. datetime模块
```python
from datetime import datetime, date, timedelta
# 当前时间
now = datetime.now()
print(f"当前时间: {now}")
print(f"日期: {now.date()}")
print(f"时间: {now.time()}")
# 格式化时间
formatted = now.strftime("%Y年%m月%d日 %H时%M分%S秒")
print(formatted) # 2023年12月15日 14时30分25秒
# 时间计算
>
tomorrow = now + one_day
last_week = now - timedelta(weeks=1)
# 解析字符串
date_str = "2023-12-15 14:30:00"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(parsed_date)
```
## 并发编程基础
### 27. 多线程
```python
import threading
import time
def worker(name, delay):
"""工作线程函数"""
print(f"线程 {name} 开始工作")
time.sleep(delay)
print(f"线程 {name} 完成工作")
# 创建线程
threads = []
for i in range(3):
t = threading.Thread(target=worker, args=(f"工作线程{i}", i+1))
threads.append(t)
t.start()
# 等待所有线程完成
for t in threads:
t.join()
print("所有线程执行完毕")
```
### 28. 多进程
```python
import multiprocessing
import os
def cpu_intensive_task(number):
"""CPU密集型任务"""
result = sum(i * i for i in range(number))
print(f"进程 {os.getpid()} 计算结果: {result}")
return result
if __name__ == "__main__":
numbers = [1000000, 2000000, 3000000]
# 创建进程池
with multiprocessing.Pool(processes=3) as pool:
results = pool.map(cpu_intensive_task, numbers)
print(f"所有结果: {results}")
```
## 第三方库入门
### 29. requests网络请求
```python
import requests
# GET请求
response = requests.get("https://api.github.com")
print(f"状态码: {response.status_code}")
print(f"内容类型: {response.headers['content-type']}")
# 带参数的GET请求
params = {"q": "python", "page": 1}
response = requests.get("https://api.github.com/search/repositories", params=params)
# POST请求
data = {"username": "张三", "password": "123456"}
response = requests.post("https://example.com/login", data=data)
# 处理JSON响应
if response.status_code == 200:
json_data = response.json()
print(json_data)
```
### 30. pandas数据处理
```python
import pandas as pd
# 创建DataFrame
data = {
"姓名": ["张三", "李四", "王五"],
"年龄": [25, 30, 35],
"城市": ["北京", "上海", "广州"]
}
df = pd.DataFrame(data)
print(df)
<"mhb.q6k0.org.cn"><"blog.q6k0.org.cn"><"share.q6k0.org.cn">
# 基本操作
print(df["姓名"]) # 选择列
print(df.iloc[0]) # 选择行
print(df.describe()) # 统计描述
# 数据筛选
young_people = df[df["年龄"] < 30]
print(young_people)
```
## 调试与测试
### 31. 调试技巧
```python
# print调试
def calculate_total(items):
print(f"[调试] 输入项: {items}") # 打印输入
total = sum(items)
print(f"[调试] 计算结果: {total}") # 打印中间结果
return total
# 使用assert断言
def divide(a, b):
assert b != 0, "除数不能为零" # 断言检查
return a / b
# pdb调试器
import pdb
def complex_calculation(x, y):
result = x * y
pdb.set_trace() # 设置断点
result += 100
return result
# 调用函数进入调试
# complex_calculation(10, 20)
# 单元测试示例
import unittest
def add(a, b):
return a + b
class TestMathFunctions(unittest.TestCase):
def test_add(self):
self.assertEqual(add(1, 2), 3)
self.assertEqual(add(-1, 1), 0)
self.assertEqual(add(0, 0), 0)
if __name__ == "__main__":
unittest.main()
```
## 学习建议与资源
掌握这31个核心知识点后,建议通过以下方式巩固学习:
1. **实践项目**:尝试小型项目如数据爬虫、Web应用、自动化脚本
2. **代码阅读**:阅读优秀开源项目的源代码
3. **持续练习**:定期解决算法问题,参加编程挑战
4. **社区参与**:加入Python社区,参与讨论和贡献
Python的学习是一个持续的过程,这些核心知识点为您打下了坚实的基础。随着编程经验的积累,您会发现Python在各领域的强大应用能力。记住,编程不仅是语法学习,更是解决问题的思维训练。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/19545/viewspace-3108518/ ,如需转载,请注明出处,否则将追究法律责任。