Python数据结构 一、数据结构概述
Python主要数据结构分类
数据结构
可变性
有序性
元素要求
示例
列表(list)
可变
有序
无
[1, 2, 3]
元组(tuple)
不可变
有序
无
(1, 2, 3)
字典(dict)
可变
无序(3.7+有序插入)
键必须可哈希
{‘a’:1, ‘b’:2}
集合(set)
可变
无序
必须可哈希
{1, 2, 3}
字符串(str)
不可变
有序
字符
“hello”
选择数据结构的考量因素
• 数据是否需要修改:可变 vs 不可变
• 是否需要保持插入顺序
• 是否需要快速查找
• 数据元素的唯一性要求
• 内存使用效率
二、列表(List):最灵活的有序集合
列表基础操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 numbers = [1 , 2 , 3 , 4 , 5 ] mixed = [1 , "hello" , 3.14 , True ] print (numbers[0 ]) print (numbers[-1 ]) numbers[1 ] = 20 print (numbers[1 :4 ]) print (numbers[:3 ]) print (numbers[2 :])
常用列表方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 fruits = ["apple" , "banana" ] fruits.append("orange" ) fruits.insert(1 , "pear" ) fruits.remove("banana" ) popped = fruits.pop(1 ) del fruits[0 ] fruits.extend(["grape" , "kiwi" ]) fruits.reverse() fruits.sort() print (fruits.count("apple" )) print (fruits.index("kiwi" ))
列表推导式
1 2 3 4 5 6 7 8 9 squares = [x**2 for x in range (10 )] even_squares = [x**2 for x in range (10 ) if x % 2 == 0 ] matrix = [[1 , 2 , 3 ], [4 , 5 , 6 ], [7 , 8 , 9 ]] flattened = [num for row in matrix for num in row]
列表性能考虑
• 时间复杂度:
• 索引/赋值:O(1)
• append/pop:O(1)
• insert/remove:O(n)
• 内存预分配:列表会预留额外空间以减少频繁扩容
• 浅拷贝与深拷贝:
1 2 3 4 5 import copyoriginal = [[1 , 2 ], [3 , 4 ]] shallow = copy.copy(original) deep = copy.deepcopy(original)
三、元组(Tuple):不可变有序集合
元组基本特性
1 2 3 4 5 6 7 8 9 10 11 12 coordinates = (10 , 20 ) single_element = (42 ,) empty_tuple = () x, y = coordinates print (x) a, b = 1 , 2 a, b = b, a
元组与列表的比较
特性
列表
元组
可变性
可变
不可变
内存占用
较大
较小
安全性
较低
较高
使用场景
需要修改的数据
固定数据、字典键
命名元组
1 2 3 4 5 6 7 8 from collections import namedtuplePoint = namedtuple('Point' , ['x' , 'y' ]) p = Point(10 , 20 ) print (p.x, p.y)
四、字典(Dict):高效的键值对存储
字典基础操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 person = {"name" : "Alice" , "age" : 25 } empty_dict = {} print (person["name" ]) print (person.get("height" , 170 )) person["email" ] = "alice@example.com" person["age" ] = 26 del person["age" ]popped_value = person.pop("name" )
字典方法
1 2 3 4 5 6 7 8 9 10 11 12 student = {"name" : "Bob" , "age" : 20 } print (student.keys()) print (student.values()) print (student.items()) student.update({"age" : 21 , "grade" : "A" }) squares = {x: x**2 for x in range (5 )}
字典视图对象
Python 3中的keys(), values(), items()返回视图对象:
1 2 3 4 5 d = {'a' : 1 , 'b' : 2 } keys = d.keys() d['c' ] = 3 print (keys)
有序字典
1 2 3 4 5 6 7 from collections import OrderedDictordered = OrderedDict() ordered['a' ] = 1 ordered['b' ] = 2 ordered['c' ] = 3
默认字典
1 2 3 4 5 6 from collections import defaultdictword_counts = defaultdict(int ) for word in ["apple" , "banana" , "apple" ]: word_counts[word] += 1
五、集合(Set):唯一元素的无序集合
集合基础
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 primes = {2 , 3 , 5 , 7 } empty_set = set () primes.add(11 ) primes.remove(2 ) primes.discard(3 ) a = {1 , 2 , 3 } b = {3 , 4 , 5 } print (a | b) print (a & b) print (a - b) print (a ^ b)
集合推导式
1 2 words = ["apple" , "banana" , "apple" , "orange" ] unique_lengths = {len (word) for word in words}
不可变集合
1 2 frozen = frozenset ([1 , 2 , 3 ])
六、高级数据结构
堆队列(heapq)
1 2 3 4 5 6 7 import heapqnums = [5 , 7 , 9 , 1 , 3 ] heapq.heapify(nums) print (heapq.heappop(nums)) heapq.heappush(nums, 2 )
双端队列(deque)
1 2 3 4 5 6 from collections import dequed = deque([1 , 2 , 3 ]) d.appendleft(0 ) d.extendleft([-1 , -2 ]) d.rotate(1 )
计数器(Counter)
1 2 3 4 5 from collections import Counterwords = ["apple" , "banana" , "apple" , "orange" ] word_counts = Counter(words) print (word_counts.most_common(2 ))
七、数据结构选择指南
常见场景推荐
需求
推荐数据结构
快速查找/映射
字典
唯一元素存储
集合
有序数据,频繁修改
列表
固定数据,作为键
元组
先进先出队列
deque
优先级队列
heapq
元素计数
Counter
性能优化技巧
预分配列表空间:lst = [None] * 1000
使用生成器表达式处理大数据:sum(x**2 for x in range(1000000))
字典代替多个if-else:使用字典查找代替复杂条件判断
集合去重:最快去重方法list(set(duplicates))
利用切片:避免不必要的列表复制
八、实际应用案例
使用字典统计词频
1 2 3 4 5 def word_frequency (text ): word_count = {} for word in text.lower().split(): word_count[word] = word_count.get(word, 0 ) + 1 return word_count
使用集合检查重复
1 2 def has_duplicates (items ): return len (items) != len (set (items))
使用堆实现Top K问题
1 2 3 4 import heapqdef top_k_largest (nums, k ): return heapq.nlargest(k, nums)
使用双端队列实现滑动窗口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 from collections import dequedef sliding_window_max (nums, k ): dq = deque() result = [] for i, num in enumerate (nums): while dq and nums[dq[-1 ]] <= num: dq.pop() dq.append(i) if dq[0 ] == i - k: dq.popleft() if i >= k - 1 : result.append(nums[dq[0 ]]) return result