Python提供了多种内置的数据结构,如列表(list)、元组(tuple)、集合(set)和字典(dictionary),它们在数据处理和分析中非常有用。以下是一些常见的数据结构及其应用示例:
列表(List):
scores = [90, 85, 78, 92] # 存储学生的成绩
元组(Tuple):
coordinates = (3, 4) # 表示二维平面上的点
集合(Set):
unique_numbers = {1, 2, 3, 4, 4, 5} # 去除重复的数字
common_elements = {1, 2} & {2, 3} # 求两个集合的交集
字典(Dictionary):
student_info = {'name': 'Alice', 'age': 20, 'major': 'Computer Science'}
# 快速查找学生的年龄
age = student_info['age']
栈(Stack):
stack = []
stack.append(1) # 入栈
stack.append(2)
stack.pop() # 出栈
队列(Queue):
from collections import deque
queue = deque()
queue.append(1) # 入队
queue.popleft() # 出队
链表(LinkedList):
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
树(Tree):
class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
# 构建二叉搜索树
root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(15)
root.left.left = TreeNode(3)
root.left.right = TreeNode(7)
图(Graph):
from collections import defaultdict
graph = defaultdict(list)
graph['A'].append('B')
graph['A'].append('C')
graph['B'].append('D')
graph['B'].append('E')
graph['C'].append('F')
这些数据结构在不同的应用场景中有各自的优势和适用性。了解并掌握它们的使用方法对于编写高效、可维护的Python代码至关重要。