Python提供了多種內(nèi)置的數(shù)據(jù)結(jié)構(gòu),如列表(list)、元組(tuple)、集合(set)和字典(dictionary),它們在數(shù)據(jù)處理和分析中非常有用。以下是一些常見的數(shù)據(jù)結(jié)構(gòu)及其應(yīng)用示例:
列表(List):
scores = [90, 85, 78, 92] # 存儲學(xué)生的成績
元組(Tuple):
coordinates = (3, 4) # 表示二維平面上的點
集合(Set):
unique_numbers = {1, 2, 3, 4, 4, 5} # 去除重復(fù)的數(shù)字
common_elements = {1, 2} & {2, 3} # 求兩個集合的交集
字典(Dictionary):
student_info = {'name': 'Alice', 'age': 20, 'major': 'Computer Science'}
# 快速查找學(xué)生的年齡
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
# 構(gòu)建二叉搜索樹
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')
這些數(shù)據(jù)結(jié)構(gòu)在不同的應(yīng)用場景中有各自的優(yōu)勢和適用性。了解并掌握它們的使用方法對于編寫高效、可維護(hù)的Python代碼至關(guān)重要。