🎯 学习目标

  • 回顾Python基础语法要点
  • 掌握数据结构的高效用法
  • 理解Python的内存管理
  • 熟悉AI开发常用语法模式

📦 数据类型

基本类型

# 数值类型 integer = 42 float_num = 3.14159 complex_num = 1 + 2j # 布尔类型 is_true = True is_false = False # 字符串 text = "Hello AI" multi_line = """ 多行字符串 """ # None类型 null_value = None

容器类型

# 列表(可变) lst = [1, 2, 3, "a", "b"] # 元组(不可变) tpl = (1, 2, 3) # 字典 dct = {"name": "AI", "version": 2.0} # 集合(无序、唯一) st = {1, 2, 3, 3} # {1, 2, 3}

🔄 列表推导式

高效的数据处理

# 基本形式 squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # 带条件过滤 evens = [x for x in range(20) if x % 2 == 0] # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] # 嵌套推导 matrix = [[i*j for j in range(5)] for i in range(5)] # 字典推导 word_lengths = {word: len(word) for word in ["AI", "ML", "DL"]} # {'AI': 2, 'ML': 2, 'DL': 2} # 集合推导 unique_lengths = {len(word) for word in ["a", "bb", "ccc"]} # {1, 2, 3}

生成器与迭代器

生成器

惰性计算,节省内存

# 生成器表达式 gen = (x**2 for x in range(1000000)) # 不立即计算,按需生成 # 生成器函数 def fibonacci(n): a, b = 0, 1 for _ in range(n): yield a a, b = b, a + b # 使用 for num in fibonacci(10): print(num)

迭代器协议

class Counter: def __init__(self, n): self.n = n self.current = 0 def __iter__(self): return self def __next__(self): if self.current < self.n: self.current += 1 return self.current raise StopIteration # 使用 for i in Counter(5): print(i) # 1, 2, 3, 4, 5

🔐 作用域与闭包

# LEGB规则: Local → Enclosing → Global → Built-in x = "global" def outer(): x = "enclosing" def inner(): x = "local" print(x) # local inner() print(x) # enclosing outer() print(x) # global # 闭包示例 def make_multiplier(n): def multiplier(x): return x * n return multiplier double = make_multiplier(2) print(double(5)) # 10

📝 本节小结

  • • Python有丰富的基本数据类型和容器类型
  • • 列表推导式提供简洁的数据处理方式
  • • 生成器适合处理大规模数据
  • • 理解作用域对调试很重要