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代碼至關重要。