Python核心语法与数据结构详解

一、基础语法精要

1. 变量与动态类型

Python使用动态类型系统,变量无需声明类型:

counter = 10          # 整数
price = 9.99          # 浮点数
name = "Alice"        # 字符串
is_active = True      # 布尔值

实践建议

  • 使用有意义的变量名(如user_count而非uc
  • 避免频繁改变变量类型(虽然Python允许)

2. 运算符优先级

图1

关键运算符

# 海象运算符(Python 3.8+)
if (n := len(data)) > 10:
    print(f"数据过长({n}项)")

二、数据结构深度解析

1. 列表(List) vs 元组(Tuple)

特性列表元组
可变性可变不可变
语法[1, 2, 3](1, 2, 3)
性能稍慢更快
使用场景动态数据集合固定数据记录

示例

# 列表推导式
squares = [x**2 for x in range(10) if x % 2 == 0]

# 元组解包
point = (3, 4)
x, y = point

2. 字典(Dict)高级用法

# 字典合并(Python 3.9+)
defaults = {"color": "red", "size": "medium"}
custom = {"size": "large", "price": 100}
combined = defaults | custom

# 字典推导式
square_dict = {x: x*x for x in range(5)}

实践建议

  • 使用.get()方法避免KeyError
  • 考虑collections.defaultdict处理缺失键

三、流程控制实战技巧

1. 条件表达式

# 传统写法
if score >= 60:
    result = "及格"
else:
    result = "不及格"

# 三元表达式
result = "及格" if score >= 60 else "不及格"

2. 循环优化

# 使用enumerate获取索引
for idx, value in enumerate(data):
    print(f"索引{idx}: {value}")

# 使用zip并行迭代
names = ["Alice", "Bob"]
scores = [85, 92]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

四、函数设计原则

1. 参数处理

def process_data(data, *, sort=False, reverse=False):
    """使用关键字参数强制命名"""
    if sort:
        data = sorted(data, reverse=reverse)
    return data

# 正确调用
process_data([3,1,2], sort=True)

2. 闭包应用

def make_counter():
    count = 0
    def counter():
        nonlocal count
        count += 1
        return count
    return counter

c = make_counter()
print(c(), c())  # 输出: 1 2

五、面向对象编程精髓

1. 类与继承

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        raise NotImplementedError

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

# 使用
dog = Dog("Buddy")
print(dog.speak())

2. 魔术方法示例

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

v1 = Vector(2, 4)
v2 = Vector(3, 1)
print(v1 + v2)  # 输出: Vector(5, 5)

六、异常处理最佳实践

def divide_file(path):
    try:
        with open(path) as f:
            content = f.read()
        numerator, denominator = map(int, content.split('/'))
        result = numerator / denominator
    except FileNotFoundError:
        print("文件不存在")
    except ValueError:
        print("文件内容格式错误")
    except ZeroDivisionError:
        print("除数不能为零")
    else:
        print(f"结果为: {result}")
    finally:
        print("处理完成")

建议

  • 捕获特定异常而非裸except
  • 使用else块处理成功情况
  • 资源清理放在finally

七、标准库高效用法

1. 文件操作

from pathlib import Path

# 现代文件操作
data_dir = Path("data")
output_file = data_dir / "output.txt"

with output_file.open("w") as f:
    f.write("Hello, Pathlib!")

2. 时间处理

from datetime import datetime, timedelta

now = datetime.now()
tomorrow = now + timedelta(days=1)
print(f"现在: {now:%Y-%m-%d %H:%M}")
print(f"明天此时: {tomorrow:%Y-%m-%d %H:%M}")

性能优化小贴士

  1. 选择合适的数据结构

    • 频繁查找用字典而非列表
    • 不可变数据考虑使用元组
  2. 减少全局变量访问

    # 慢
    def calculate():
        return len(GLOBAL_LIST) * 2
    
    # 快
    def calculate(lst):
        return len(lst) * 2
  3. 使用生成器处理大数据

    def read_large_file(file_path):
        with open(file_path) as f:
            for line in f:
                yield line.strip()
    
    # 使用
    for line in read_large_file("huge.log"):
        process(line)

掌握这些核心语法和数据结构是成为Python高手的基础,建议通过实际项目不断练习巩固这些概念。

添加新评论