概覽
- 列表操作(增刪改查/切片/推導式)
- 元組特性與不可變性
- 字典操作(鍵值對/嵌套字典)
- 集合運算(交集/并集/差集)
Python的核心數據結構是編程的基石,本文將系統講解列表、元組、字典和集合四大數據結構,包含詳細的教學內容和實用示例。
一、列表:靈活的可變序列
列表是Python中最常用的數據結構,支持存儲不同類型元素,并允許動態修改。
創建與基本操作
# 創建列表
fruits = ["apple", "banana", "cherry"]
numbers = [1, 3.14, True] # 支持混合類型# 索引訪問(正向從0開始,負向從-1開始)
print(fruits[0]) # "apple"
print(fruits[-1]) # "cherry"# 添加元素
fruits.append("orange") # 末尾添加 ["apple", "banana", "cherry", "orange"]
fruits.insert(1, "mango") # 指定位置插入 ["apple", "mango", "banana", "cherry", "orange"]# 刪除元素
fruits.remove("banana") # 按值刪除
popped = fruits.pop(2) # 按索引刪除并返回被刪元素
del fruits[0:2] # 刪除切片 ["cherry", "orange"]# 修改元素
fruits[0] = "kiwi" # 直接賦值修改
切片操作詳解
切片語法:
list[start:stop:step]
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]# 基礎切片
print(numbers[2:5]) # [2, 3, 4] 索引2到5(不含5)
print(numbers[:3]) # [0, 1, 2] 從頭開始
print(numbers[7:]) # [7, 8, 9] 直到末尾# 步長切片
print(numbers[::2]) # [0, 2, 4, 6, 8] 每隔一個取
print(numbers[1::2]) # [1, 3, 5, 7, 9] 奇數索引
print(numbers[::-1]) # [9, 8, 7, ...] 逆序列表# 切片復制
copy = numbers[:] # 創建全新列表副本
列表推導式實戰
列表推導式提供簡潔高效的創建方式:
# 基礎推導式
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]# 條件過濾
even_squares = [x**2 for x in range(10) if x % 2 == 0] # [0, 4, 16, 36, 64]# 嵌套推導式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row] # [1, 2, 3, 4, 5, 6, 7, 8, 9]# 帶條件轉換
grades = [85, 92, 78, 90, 65]
result = ["Pass" if score >= 70 else "Fail" for score in grades] # ['Pass', 'Pass', 'Pass', 'Pass', 'Fail']
二、元組:不可變的守護者
元組與列表類似,但創建后不可修改,適合存儲不應改變的數據。
創建與特性
# 創建元組
colors = ("red", "green", "blue")
coordinates = (40.7128, -74.0060) # 經緯度數據# 單元素元組需加逗號
single = ("only",) # 注意逗號
not_tuple = ("oops") # 這實際是字符串# 解包賦值
x, y, z = colors # x="red", y="green", z="blue"# 不可變性驗證
try:colors[1] = "yellow" # 嘗試修改
except TypeError as e:print(f"錯誤:{e}") # 'tuple' object does not support item assignment
元組的實際應用場景
# 1. 函數返回多個值
def get_dimensions():return 1920, 1080width, height = get_dimensions()# 2. 字典鍵值(列表不能作為鍵)
locations = {(35.6895, 139.6917): "Tokyo",(40.7128, -74.0060): "New York"
}# 3. 保護重要數據
CONFIG = ("admin", "secure_password", 8080)
# 后續無法修改CONFIG內容# 4. 格式化字符串
print("%s 的坐標是 (%.2f, %.2f)" % ("東京", 35.68, 139.69))
元組vs列表性能對比
import sys
import timeitlist_size = sys.getsizeof([1, 2, 3, 4, 5]) # 112 bytes
tuple_size = sys.getsizeof((1, 2, 3, 4, 5)) # 88 byteslist_time = timeit.timeit("x = [1, 2, 3, 4, 5]", number=1000000) # 約0.06秒
tuple_time = timeit.timeit("x = (1, 2, 3, 4, 5)", number=1000000) # 約0.02秒
三、字典:高效的鍵值映射
字典通過哈希表實現,具有O(1)時間復雜度的查找效率。
基礎操作詳解
# 創建字典
student = {"name": "Alice","age": 20,"courses": ["Math", "Physics"]
}# 增/改元素
student["email"] = "alice@example.com" # 新增
student["age"] = 21 # 修改# 刪除元素
del student["courses"] # 刪除鍵值對
age = student.pop("age") # 刪除并返回值# 查詢元素
print(student["name"]) # 直接訪問(鍵不存在會報錯)
print(student.get("phone", "N/A")) # 安全訪問,不存在返回默認值# 遍歷字典
for key in student: # 遍歷鍵print(key)for key, value in student.items(): # 同時遍歷鍵值print(f"{key}: {value}")
嵌套字典實戰
# 多層嵌套結構
university = {"departments": {"CS": {"head": "Dr. Smith","courses": ["Algorithms", "AI"]},"Math": {"head": "Dr. Johnson","courses": ["Calculus", "Statistics"]}},"students": 15000
}# 訪問嵌套值
print(university["departments"]["CS"]["courses"][0]) # "Algorithms"# 修改嵌套值
university["departments"]["Math"]["head"] = "Dr. Brown"# 添加新系
university["departments"]["Physics"] = {"head": "Dr. Wilson","courses": ["Mechanics", "Quantum Physics"]
}# 安全訪問深層次鍵
from collections import defaultdict
grades = defaultdict(lambda: "N/A", {"Math": "A", "Physics": "B"})
print(grades["Chemistry"]) # 輸出 "N/A" 而不報錯
字典推導式
# 基本推導式
numbers = [1, 2, 3, 4]
squares = {x: x**2 for x in numbers} # {1: 1, 2: 4, 3: 9, 4: 16}# 條件過濾
even_squares = {x: x**2 for x in numbers if x % 2 == 0} # {2: 4, 4: 16}# 鍵值轉換
student = {"name": "Alice", "age": 20}
uppercase = {key.upper(): str(value).upper() for key, value in student.items()} # {"NAME": "ALICE", "AGE": "20"}
四、集合:無序且唯一
集合用于存儲不重復元素,支持數學集合運算。
基本操作
# 創建集合
primes = {2, 3, 5, 7, 11}
evens = set([2, 4, 6, 8, 10])# 添加元素
primes.add(13) # {2, 3, 5, 7, 11, 13}
primes.add(3) # 重復元素自動忽略# 刪除元素
primes.remove(2) # 刪除存在的元素
primes.discard(4) # 安全刪除(元素不存在不報錯)# 集合運算
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}print(A | B) # 并集 {1, 2, 3, 4, 5, 6}
print(A & B) # 交集 {3, 4}
print(A - B) # 差集 {1, 2}
print(A ^ B) # 對稱差 {1, 2, 5, 6}# 成員測試(O(1)時間復雜度)
if 5 in B:print("5在集合B中")
集合實際應用
# 1. 數據去重
words = ["hello", "world", "hello", "python", "world"]
unique_words = set(words) # {"hello", "world", "python"}# 2. 關系測試
developers = {"Alice", "Bob", "Charlie"}
designers = {"Bob", "David", "Eve"}
both_roles = developers & designers # {"Bob"}# 3. 過濾重復內容
emails = ["a@test.com", "b@test.com", "a@test.com", "c@test.com"]
unique_emails = list(set(emails)) # 去重后轉回列表# 4. 大型數據成員測試(效率遠高于列表)
big_set = set(range(1000000))
%timeit 999999 in big_set # 約 0.03 毫秒big_list = list(range(1000000))
%timeit 999999 in big_list # 約 12 毫秒
數據結構對比與選型指南
特性 | 列表(List) | 元組(Tuple) | 字典(Dict) | 集合(Set) |
---|---|---|---|---|
可變性 | 可變 | 不可變 | 可變 | 可變 |
排序 | 有序 | 有序 | 無序(Python3.7+有序) | 無序 |
元素特性 | 可重復 | 可重復 | 鍵唯一 | 元素唯一 |
查找速度 | O(n) | O(n) | O(1) | O(1) |
內存占用 | 中等 | 較小 | 較大 | 較大 |
典型應用 | 同質數據序列 | 數據保護/常量 | 鍵值映射 | 去重/集合運算 |
選型決策樹:
- 需要修改元素? → 列表(有序數據)/字典(鍵值對)
- 需要保護數據不被修改? → 元組
- 需要快速查找元素? → 字典(按鍵查找)/集合(按值查找)
- 需要去重? → 集合
- 需要數學集合運算? → 集合
最佳實踐建議:
- 使用元組存儲不應更改的數據(如配置常量)
- 優先選擇字典進行鍵值映射,特別是大型數據集
- 使用集合推導式比循環更高效
- 切片操作時注意:start包含,end不包含
- 字典鍵必須為不可變類型(字符串、數字、元組)
掌握這些核心數據結構及其特性,能夠根據具體需求選擇最合適的工具,大幅提升代碼效率和可讀性。
本文由元來智聯開發團隊出品:元來智聯-網站、小程序等定制開發,專業開發服務商