Python基礎-數據結構

數據結構

Python提供了四種主要的內置數據結構:列表(List)、元組(Tuple)、字典(Dictionary)和集合(Set)。每種數據結構都有其特定的用途和特性。

Python數據結構概覽:
┌─────────────────────────────────────────────┐
│                數據結構分類                 │
├─────────────────────────────────────────────┤
│ 序列類型(有序):                          │
│   ? 列表 [1,2,3]     - 可變,可重復        │
│   ? 元組 (1,2,3)     - 不可變,可重復      │
│   ? 字符串 "abc"     - 不可變,可重復      │
│                                             │
│ 映射類型:                                  │
│   ? 字典 {k:v}       - 可變,鍵唯一        │
│                                             │
│ 集合類型:                                  │
│   ? 集合 {1,2,3}     - 可變,元素唯一      │
└─────────────────────────────────────────────┘

列表(List)

列表是Python中最常用的數據結構,用方括號 [] 表示,元素之間用逗號分隔。

1. 創建列表

# 空列表
empty_list = []
print(f"空列表: {empty_list}")# 包含元素的列表
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
mixed = [1, "hello", 3.14, True, None]print(f"數字列表: {numbers}")
print(f"水果列表: {fruits}")
print(f"混合列表: {mixed}")# 使用list()函數創建
list_from_string = list("hello")
list_from_range = list(range(5))print(f"從字符串創建: {list_from_string}")
print(f"從range創建: {list_from_range}")# 列表推導式創建
squares = [x**2 for x in range(1, 6)]
even_numbers = [x for x in range(10) if x % 2 == 0]print(f"平方數列表: {squares}")
print(f"偶數列表: {even_numbers}")

2. 訪問、修改、刪除元素

fruits = ["apple", "banana", "orange", "grape", "kiwi"]
print(f"原始列表: {fruits}")# 訪問元素(索引從0開始)
print(f"第一個元素: {fruits[0]}")
print(f"最后一個元素: {fruits[-1]}")
print(f"倒數第二個: {fruits[-2]}")# 切片訪問
print(f"前三個元素: {fruits[:3]}")
print(f"后兩個元素: {fruits[-2:]}")
print(f"中間元素: {fruits[1:4]}")
print(f"每隔一個: {fruits[::2]}")
print(f"反向列表: {fruits[::-1]}")# 修改元素
fruits[1] = "blueberry"
print(f"修改后: {fruits}")# 修改多個元素
fruits[2:4] = ["mango", "pineapple"]
print(f"批量修改: {fruits}")# 刪除元素
del fruits[0]  # 刪除指定索引的元素
print(f"刪除第一個元素: {fruits}")del fruits[1:3]  # 刪除切片
print(f"刪除切片: {fruits}")

3. 列表方法

# 創建示例列表
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(f"原始列表: {numbers}")# append() - 在末尾添加元素
numbers.append(8)
print(f"append(8): {numbers}")# insert() - 在指定位置插入元素
numbers.insert(2, 99)
print(f"insert(2, 99): {numbers}")# extend() - 擴展列表
numbers.extend([10, 11])
print(f"extend([10, 11]): {numbers}")# remove() - 刪除第一個匹配的元素
numbers.remove(1)
print(f"remove(1): {numbers}")# pop() - 刪除并返回指定位置的元素
popped = numbers.pop()  # 默認刪除最后一個
print(f"pop(): {numbers}, 刪除的元素: {popped}")popped_index = numbers.pop(0)  # 刪除指定位置
print(f"pop(0): {numbers}, 刪除的元素: {popped_index}")# index() - 查找元素的索引
index_of_4 = numbers.index(4)
print(f"4的索引: {index_of_4}")# count() - 統計元素出現次數
count_of_1 = numbers.count(1)
print(f"1出現的次數: {count_of_1}")# sort() - 原地排序
numbers_copy = numbers.copy()
numbers_copy.sort()
print(f"升序排序: {numbers_copy}")numbers_copy.sort(reverse=True)
print(f"降序排序: {numbers_copy}")# reverse() - 反轉列表
numbers.reverse()
print(f"反轉列表: {numbers}")# clear() - 清空列表
temp_list = [1, 2, 3]
temp_list.clear()
print(f"清空后: {temp_list}")

4. 列表的高級操作

# 列表合并
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(f"列表合并: {combined}")# 列表重復
repeated = [0] * 5
print(f"重復列表: {repeated}")# 列表比較
print(f"[1,2,3] == [1,2,3]: {[1,2,3] == [1,2,3]}")
print(f"[1,2,3] < [1,2,4]: {[1,2,3] < [1,2,4]}")# 嵌套列表
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(f"矩陣: {matrix}")
print(f"第二行第三列: {matrix[1][2]}")# 列表解包
a, b, c = [1, 2, 3]
print(f"解包: a={a}, b={b}, c={c}")# 使用*解包
first, *middle, last = [1, 2, 3, 4, 5]
print(f"解包: first={first}, middle={middle}, last={last}")

元組(Tuple)

元組是不可變的有序集合,用圓括號 () 表示。

1. 創建元組

# 空元組
empty_tuple = ()
print(f"空元組: {empty_tuple}")# 包含元素的元組
coordinates = (3, 4)
colors = ("red", "green", "blue")
mixed_tuple = (1, "hello", 3.14, True)print(f"坐標: {coordinates}")
print(f"顏色: {colors}")
print(f"混合元組: {mixed_tuple}")# 單元素元組(注意逗號)
single_tuple = (42,)  # 必須有逗號
print(f"單元素元組: {single_tuple}")
print(f"類型: {type(single_tuple)}")# 不帶括號也可以創建元組
point = 1, 2, 3
print(f"不帶括號的元組: {point}")
print(f"類型: {type(point)}")# 使用tuple()函數創建
tuple_from_list = tuple([1, 2, 3, 4])
tuple_from_string = tuple("hello")print(f"從列表創建: {tuple_from_list}")
print(f"從字符串創建: {tuple_from_string}")

2. 訪問元素

fruits = ("apple", "banana", "orange", "grape")
print(f"水果元組: {fruits}")# 索引訪問
print(f"第一個水果: {fruits[0]}")
print(f"最后一個水果: {fruits[-1]}")# 切片訪問
print(f"前兩個水果: {fruits[:2]}")
print(f"后兩個水果: {fruits[-2:]}")# 元組解包
first, second, third, fourth = fruits
print(f"解包: {first}, {second}, {third}, {fourth}")# 部分解包
first, *others = fruits
print(f"第一個: {first}, 其他: {others}")# 交換變量(利用元組)
a, b = 10, 20
print(f"交換前: a={a}, b={b}")
a, b = b, a
print(f"交換后: a={a}, b={b}")

3. 元組的方法和特性

numbers = (1, 2, 3, 2, 4, 2, 5)
print(f"數字元組: {numbers}")# count() - 統計元素出現次數
count_of_2 = numbers.count(2)
print(f"2出現的次數: {count_of_2}")# index() - 查找元素的索引
index_of_3 = numbers.index(3)
print(f"3的索引: {index_of_3}")# len() - 獲取長度
print(f"元組長度: {len(numbers)}")# 成員檢測
print(f"3 in numbers: {3 in numbers}")
print(f"6 not in numbers: {6 not in numbers}")# 元組比較
print(f"(1,2,3) < (1,2,4): {(1,2,3) < (1,2,4)}")
print(f"(1,2,3) == (1,2,3): {(1,2,3) == (1,2,3)}")# 嵌套元組
nested = ((1, 2), (3, 4), (5, 6))
print(f"嵌套元組: {nested}")
print(f"訪問嵌套元素: {nested[1][0]}")

4. 元組的應用場景

# 1. 函數返回多個值
def get_name_age():return "Alice", 25name, age = get_name_age()
print(f"姓名: {name}, 年齡: {age}")# 2. 作為字典的鍵(因為不可變)
locations = {(0, 0): "原點",(1, 1): "右上",(-1, -1): "左下"
}
print(f"坐標字典: {locations}")
print(f"(1,1)位置: {locations[(1, 1)]}")# 3. 配置信息
DATABASE_CONFIG = ("localhost",  # host5432,         # port"mydb",       # database"user",       # username"password"    # password
)host, port, db, user, pwd = DATABASE_CONFIG
print(f"數據庫配置: {host}:{port}/{db}")# 4. 枚舉替代
STATUS_PENDING = 0
STATUS_RUNNING = 1
STATUS_COMPLETED = 2STATUS_NAMES = ("待處理", "運行中", "已完成")
status = STATUS_RUNNING
print(f"當前狀態: {STATUS_NAMES[status]}")

字典(Dictionary)

字典是鍵值對的集合,用花括號 {} 表示,鍵和值之間用冒號 : 分隔。

1. 創建字典

# 空字典
empty_dict = {}
print(f"空字典: {empty_dict}")# 包含元素的字典
student = {"name": "張三","age": 20,"grade": "A","subjects": ["數學", "英語", "物理"]
}
print(f"學生信息: {student}")# 使用dict()函數創建
dict_from_pairs = dict([("a", 1), ("b", 2), ("c", 3)])
dict_from_kwargs = dict(name="李四", age=22, city="北京")print(f"從鍵值對創建: {dict_from_pairs}")
print(f"從關鍵字參數創建: {dict_from_kwargs}")# 字典推導式
squares_dict = {x: x**2 for x in range(1, 6)}
filtered_dict = {k: v for k, v in student.items() if isinstance(v, str)}print(f"平方數字典: {squares_dict}")
print(f"過濾后的字典: {filtered_dict}")

2. 訪問、修改、刪除鍵值對

student = {"name": "張三","age": 20,"grade": "A","city": "上海"
}
print(f"原始字典: {student}")# 訪問值
print(f"姓名: {student['name']}")
print(f"年齡: {student.get('age')}")
print(f"電話: {student.get('phone', '未提供')}")  # 提供默認值# 修改值
student["age"] = 21
student["grade"] = "A+"
print(f"修改后: {student}")# 添加新鍵值對
student["phone"] = "13800138000"
student["email"] = "zhangsan@example.com"
print(f"添加后: {student}")# 刪除鍵值對
del student["city"]
print(f"刪除city后: {student}")phone = student.pop("phone")  # 刪除并返回值
print(f"刪除phone: {phone}, 字典: {student}")email = student.pop("email", "無郵箱")  # 提供默認值
print(f"刪除email: {email}")

3. 字典方法

student = {"name": "張三","age": 20,"grade": "A","subjects": ["數學", "英語"]
}print(f"原始字典: {student}")# keys() - 獲取所有鍵
keys = student.keys()
print(f"所有鍵: {list(keys)}")# values() - 獲取所有值
values = student.values()
print(f"所有值: {list(values)}")# items() - 獲取所有鍵值對
items = student.items()
print(f"所有鍵值對: {list(items)}")# update() - 更新字典
student.update({"city": "北京", "phone": "13800138000"})
print(f"更新后: {student}")student.update(age=21, grade="A+")  # 使用關鍵字參數
print(f"再次更新: {student}")# setdefault() - 設置默認值
email = student.setdefault("email", "default@example.com")
print(f"設置默認email: {email}")
print(f"字典: {student}")# copy() - 淺拷貝
student_copy = student.copy()
print(f"拷貝的字典: {student_copy}")# clear() - 清空字典
temp_dict = {"a": 1, "b": 2}
temp_dict.clear()
print(f"清空后: {temp_dict}")

4. 字典的高級操作

# 字典合并(Python 3.9+)
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = dict1 | dict2
print(f"合并字典: {merged}")# 字典合并(通用方法)
dict1.update(dict2)
print(f"更新后的dict1: {dict1}")# 嵌套字典
company = {"name": "科技公司","employees": {"張三": {"age": 25, "position": "工程師"},"李四": {"age": 30, "position": "經理"},"王五": {"age": 28, "position": "設計師"}},"departments": ["技術部", "市場部", "人事部"]
}print(f"公司信息: {company['name']}")
print(f"張三的年齡: {company['employees']['張三']['age']}")# 安全訪問嵌套字典
def safe_get(dictionary, *keys):"""安全獲取嵌套字典的值"""for key in keys:if isinstance(dictionary, dict) and key in dictionary:dictionary = dictionary[key]else:return Nonereturn dictionaryage = safe_get(company, "employees", "張三", "age")
print(f"安全獲取張三年齡: {age}")# 字典遍歷
print("\n遍歷字典:")
for key in company:print(f"鍵: {key}")for key, value in company.items():if key != "employees":print(f"{key}: {value}")# 遍歷嵌套字典
print("\n員工信息:")
for name, info in company["employees"].items():print(f"{name}: {info['age']}歲, {info['position']}")

集合(Set)

集合是無序且元素唯一的集合,用花括號 {} 表示(但不包含鍵值對)。

1. 創建集合

# 空集合(注意:{}創建的是字典,不是集合)
empty_set = set()
print(f"空集合: {empty_set}")
print(f"類型: {type(empty_set)}")# 包含元素的集合
numbers = {1, 2, 3, 4, 5}
fruits = {"apple", "banana", "orange"}
mixed = {1, "hello", 3.14, True}print(f"數字集合: {numbers}")
print(f"水果集合: {fruits}")
print(f"混合集合: {mixed}")# 從其他數據結構創建集合
set_from_list = set([1, 2, 2, 3, 3, 4])  # 自動去重
set_from_string = set("hello")  # 字符去重
set_from_tuple = set((1, 2, 3, 2, 1))print(f"從列表創建(去重): {set_from_list}")
print(f"從字符串創建: {set_from_string}")
print(f"從元組創建: {set_from_tuple}")# 集合推導式
squares_set = {x**2 for x in range(1, 6)}
even_set = {x for x in range(10) if x % 2 == 0}print(f"平方數集合: {squares_set}")
print(f"偶數集合: {even_set}")

2. 集合運算

set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}
set_c = {1, 2, 3}print(f"集合A: {set_a}")
print(f"集合B: {set_b}")
print(f"集合C: {set_c}")# 并集(Union)
union1 = set_a | set_b
union2 = set_a.union(set_b)
print(f"并集 A|B: {union1}")
print(f"并集 A.union(B): {union2}")# 交集(Intersection)
intersection1 = set_a & set_b
intersection2 = set_a.intersection(set_b)
print(f"交集 A&B: {intersection1}")
print(f"交集 A.intersection(B): {intersection2}")# 差集(Difference)
difference1 = set_a - set_b
difference2 = set_a.difference(set_b)
print(f"差集 A-B: {difference1}")
print(f"差集 A.difference(B): {difference2}")# 對稱差集(Symmetric Difference)
sym_diff1 = set_a ^ set_b
sym_diff2 = set_a.symmetric_difference(set_b)
print(f"對稱差集 A^B: {sym_diff1}")
print(f"對稱差集 A.symmetric_difference(B): {sym_diff2}")# 子集和超集
print(f"C是A的子集: {set_c.issubset(set_a)}")
print(f"A是C的超集: {set_a.issuperset(set_c)}")
print(f"A和B不相交: {set_a.isdisjoint(set_b)}")
集合運算圖解:
┌─────────────────────────────────────────────┐
│              集合運算示意圖                 │
├─────────────────────────────────────────────┤
│                                             │
│    A = {1,2,3,4,5}    B = {4,5,6,7,8}      │
│                                             │
│    ┌─────────┐      ┌─────────┐             │
│    │ 1  2  3 │ 4  5 │ 6  7  8 │             │
│    │    A    │      │    B    │             │
│    └─────────┘      └─────────┘             │
│                                             │
│ 并集 A∪B = {1,2,3,4,5,6,7,8}               │
│ 交集 A∩B = {4,5}                           │
│ 差集 A-B = {1,2,3}                         │
│ 對稱差集 A△B = {1,2,3,6,7,8}               │
│                                             │
└─────────────────────────────────────────────┘

3. 集合方法

fruits = {"apple", "banana", "orange"}
print(f"原始集合: {fruits}")# add() - 添加單個元素
fruits.add("grape")
print(f"添加grape: {fruits}")# update() - 添加多個元素
fruits.update(["kiwi", "mango"])
print(f"添加多個元素: {fruits}")fruits.update("pear")  # 字符串會被拆分
print(f"添加字符串: {fruits}")# remove() - 刪除元素(不存在會報錯)
fruits.remove("p")  # 刪除字符'p'
print(f"刪除p: {fruits}")# discard() - 刪除元素(不存在不報錯)
fruits.discard("grape")
fruits.discard("nonexistent")  # 不會報錯
print(f"discard后: {fruits}")# pop() - 隨機刪除并返回一個元素
popped = fruits.pop()
print(f"隨機刪除: {popped}, 剩余: {fruits}")# clear() - 清空集合
temp_set = {1, 2, 3}
temp_set.clear()
print(f"清空后: {temp_set}")# copy() - 復制集合
fruits_copy = fruits.copy()
print(f"復制的集合: {fruits_copy}")

4. 集合的應用場景

# 1. 去重
numbers_with_duplicates = [1, 2, 2, 3, 3, 3, 4, 4, 5]
unique_numbers = list(set(numbers_with_duplicates))
print(f"原列表: {numbers_with_duplicates}")
print(f"去重后: {unique_numbers}")# 2. 成員檢測(比列表快)
large_set = set(range(1000000))
print(f"999999 in large_set: {999999 in large_set}")  # 很快# 3. 找出兩個列表的共同元素
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common = list(set(list1) & set(list2))
print(f"共同元素: {common}")# 4. 找出差異
diff1 = list(set(list1) - set(list2))
diff2 = list(set(list2) - set(list1))
print(f"list1獨有: {diff1}")
print(f"list2獨有: {diff2}")# 5. 權限管理
user_permissions = {"read", "write"}
required_permissions = {"read", "write", "execute"}has_all_permissions = required_permissions.issubset(user_permissions)
missing_permissions = required_permissions - user_permissionsprint(f"用戶權限: {user_permissions}")
print(f"需要權限: {required_permissions}")
print(f"權限足夠: {has_all_permissions}")
print(f"缺少權限: {missing_permissions}")

字符串(String)

字符串是字符的序列,在Python中是不可變的。

1. 字符串基本操作

切片操作
text = "Hello, Python!"
print(f"原字符串: {text}")# 基本切片
print(f"前5個字符: {text[:5]}")
print(f"后7個字符: {text[-7:]}")
print(f"中間部分: {text[7:13]}")
print(f"每隔一個字符: {text[::2]}")
print(f"反轉字符串: {text[::-1]}")# 步長切片
print(f"從索引1開始,每隔2個: {text[1::2]}")
print(f"倒序每隔2個: {text[::-2]}")
字符串拼接
# 使用+操作符
first_name = "張"
last_name = "三"
full_name = first_name + last_name
print(f"姓名: {full_name}")# 使用+=操作符
greeting = "Hello"
greeting += ", "
greeting += "World!"
print(f"問候: {greeting}")# 使用join()方法(推薦用于多個字符串)
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(f"句子: {sentence}")# 使用*操作符重復
line = "-" * 30
print(line)
print("標題".center(30))
print(line)
字符串格式化
name = "Alice"
age = 25
score = 95.5# 1. f-string(Python 3.6+,推薦)
formatted1 = f"姓名: {name}, 年齡: {age}, 分數: {score:.1f}"
print(formatted1)# 表達式和函數調用
formatted2 = f"明年{name}{age + 1}歲,分數是{score}{'及格' if score >= 60 else '不及格'})"
print(formatted2)# 2. str.format()方法
formatted3 = "姓名: {}, 年齡: {}, 分數: {:.1f}".format(name, age, score)
formatted4 = "姓名: {name}, 年齡: {age}, 分數: {score:.1f}".format(name=name, age=age, score=score
)
print(formatted3)
print(formatted4)# 3. %格式化(舊式,不推薦)
formatted5 = "姓名: %s, 年齡: %d, 分數: %.1f" % (name, age, score)
print(formatted5)# 格式化選項
pi = 3.14159265359
print(f"π = {pi:.2f}")      # 保留2位小數
print(f"π = {pi:.6f}")      # 保留6位小數
print(f"π = {pi:10.2f}")    # 總寬度10,右對齊
print(f"π = {pi:<10.2f}")   # 左對齊
print(f"π = {pi:^10.2f}")   # 居中對齊
print(f"π = {pi:0>10.2f}")  # 用0填充# 數字格式化
number = 1234567
print(f"數字: {number:,}")        # 千位分隔符
print(f"百分比: {0.85:.1%}")       # 百分比格式
print(f"科學計數法: {number:.2e}")  # 科學計數法

2. 字符串方法

text = "  Hello, Python World!  "
print(f"原字符串: '{text}'")# 大小寫轉換
print(f"大寫: {text.upper()}")
print(f"小寫: {text.lower()}")
print(f"首字母大寫: {text.capitalize()}")
print(f"標題格式: {text.title()}")
print(f"大小寫互換: {text.swapcase()}")# 去除空白
print(f"去除兩端空白: '{text.strip()}'")
print(f"去除左側空白: '{text.lstrip()}'")
print(f"去除右側空白: '{text.rstrip()}'")# 查找和替換
print(f"查找'Python': {text.find('Python')}")
print(f"查找'Java': {text.find('Java')}")
print(f"統計'l'的個數: {text.count('l')}")
print(f"替換'Python'為'Java': {text.replace('Python', 'Java')}")# 分割和連接
sentence = "apple,banana,orange,grape"
fruits = sentence.split(",")
print(f"分割結果: {fruits}")rejoined = " | ".join(fruits)
print(f"重新連接: {rejoined}")# 按行分割
multiline = """第一行
第二行
第三行"""
lines = multiline.splitlines()
print(f"按行分割: {lines}")# 判斷方法
test_strings = ["123", "abc", "ABC", "123abc", "  ", ""]
for s in test_strings:print(f"'{s}': 數字={s.isdigit()}, 字母={s.isalpha()}, "f"字母數字={s.isalnum()}, 空白={s.isspace()}, "f"大寫={s.isupper()}, 小寫={s.islower()}")# 對齊方法
text = "Python"
print(f"左對齊: '{text.ljust(20, '-')}'")
print(f"右對齊: '{text.rjust(20, '-')}'")
print(f"居中: '{text.center(20, '-')}'")
print(f"零填充: '{text.zfill(10)}'")# 編碼和解碼
original = "你好,世界!"
encoded = original.encode('utf-8')
decoded = encoded.decode('utf-8')
print(f"原字符串: {original}")
print(f"編碼后: {encoded}")
print(f"解碼后: {decoded}")

3. 字符串的高級操作

# 字符串模板
from string import Templatetemplate = Template("Hello, $name! You have $count new messages.")
message = template.substitute(name="Alice", count=5)
print(f"模板結果: {message}")# 安全替換(缺少變量不報錯)
partial = template.safe_substitute(name="Bob")
print(f"部分替換: {partial}")# 正則表達式(簡單介紹)
import retext = "聯系電話:138-0013-8000,郵箱:user@example.com"
phone_pattern = r'\d{3}-\d{4}-\d{4}'
email_pattern = r'\w+@\w+\.\w+'phone = re.search(phone_pattern, text)
email = re.search(email_pattern, text)if phone:print(f"找到電話: {phone.group()}")
if email:print(f"找到郵箱: {email.group()}")# 字符串性能優化
# 錯誤方式:頻繁使用+拼接
# result = ""
# for i in range(1000):
#     result += str(i)# 正確方式:使用join
numbers = [str(i) for i in range(1000)]
result = "".join(numbers)
print(f"拼接結果長度: {len(result)}")# 使用io.StringIO處理大量字符串
from io import StringIObuffer = StringIO()
for i in range(10):buffer.write(f"Line {i}\n")
result = buffer.getvalue()
print(f"StringIO結果:\n{result}")
buffer.close()

數據結構性能比較

import time
import sys# 創建測試數據
test_size = 100000
test_data = list(range(test_size))print("數據結構性能比較(基于100,000個元素):")
print("=" * 50)# 1. 內存占用比較
list_data = list(test_data)
tuple_data = tuple(test_data)
set_data = set(test_data)
dict_data = {i: i for i in test_data}print(f"列表內存占用: {sys.getsizeof(list_data):,} 字節")
print(f"元組內存占用: {sys.getsizeof(tuple_data):,} 字節")
print(f"集合內存占用: {sys.getsizeof(set_data):,} 字節")
print(f"字典內存占用: {sys.getsizeof(dict_data):,} 字節")# 2. 查找性能比較
search_value = test_size - 1# 列表查找
start = time.time()
result = search_value in list_data
list_time = time.time() - start# 集合查找
start = time.time()
result = search_value in set_data
set_time = time.time() - start# 字典查找
start = time.time()
result = search_value in dict_data
dict_time = time.time() - startprint(f"\n查找性能比較:")
print(f"列表查找時間: {list_time:.6f} 秒")
print(f"集合查找時間: {set_time:.6f} 秒")
print(f"字典查找時間: {dict_time:.6f} 秒")
print(f"集合比列表快: {list_time/set_time:.1f} 倍")
數據結構選擇指南:
┌─────────────────────────────────────────────┐
│              何時使用哪種數據結構           │
├─────────────────────────────────────────────┤
│ 列表 List:                                 │
│ ? 需要有序存儲                             │
│ ? 允許重復元素                             │
│ ? 需要頻繁修改                             │
│ ? 需要索引訪問                             │
│                                             │
│ 元組 Tuple:                                │
│ ? 數據不需要修改                           │
│ ? 作為字典的鍵                             │
│ ? 函數返回多個值                           │
│ ? 配置信息存儲                             │
│                                             │
│ 字典 Dict:                                 │
│ ? 需要鍵值對映射                           │
│ ? 快速查找和訪問                           │
│ ? 數據有明確的標識                         │
│                                             │
│ 集合 Set:                                  │
│ ? 需要去重                                 │
│ ? 集合運算(交集、并集等)                 │
│ ? 快速成員檢測                             │
│ ? 數學集合操作                             │
└─────────────────────────────────────────────┘

總結

本章詳細介紹了Python的四種主要數據結構:

  1. 列表(List): 有序、可變、允許重復的序列
  2. 元組(Tuple): 有序、不可變、允許重復的序列
  3. 字典(Dictionary): 鍵值對映射,鍵唯一
  4. 集合(Set): 無序、元素唯一的集合
  5. 字符串(String): 字符序列,不可變

每種數據結構都有其特定的應用場景和性能特點。選擇合適的數據結構對程序的效率和可讀性都很重要。


下一章預告: 控制結構 - 學習條件語句、循環語句和程序流程控制。

更多精彩文章,有問題也可以咨詢我

在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/93225.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/93225.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/93225.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

NLP學習之Transformer(1)

初識 Transformer &#xff08;1&#xff09; 1.簡介 1.1主要特點&#xff1a; self-attention&#xff1a; 自注意力機制&#xff0c;Transformer的核心是自注意力機制&#xff0c;它允許模型在處理某個位置的輸入時&#xff0c;能夠直接與其他位置的輸入交互&#xff0c;而不…

C語言筆記6:C高級 part1

1.gcc 編譯器 編譯流程 預處理-》編譯》匯編》鏈接》 E 預處理的命令 S 編譯匯編代碼 -c匯編階段命令 -o 輸出對應的文件GDB調試工具2.作用域存儲分類// C高級部分知識多&#xff0c; 加上這周 我學的知識量有點爆炸。家里又有事情&#xff0c;這周末要回老家 爭取下周補齊吧。…

A12預裝app

在A12上預裝應用&#xff0c;出現了一個異常。在此記錄問題描述&#xff1a;在A12上預裝應用按照A13的預裝方案報錯&#xff0c;mk文件如下&#xff1a;LOCAL_PATH : $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE_TAGS : optional LOCAL_MODULE : Tideen_PTT LOCAL_MODU…

termios 線程 poll epoll進化 二叉AVL紅黑樹

struct termios tio 是什么 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <termios.h>#define SERIAL_PORT "/dev/ttyS0" #define BUF_SIZE 256int main(v…

C++設計模式:類間關系

類封裝了數據和行為&#xff0c;是面向對象的重要組成部分&#xff0c;它是具有相同屬性、操作、關系的對象集合的總稱。在系統中&#xff0c;每個類都具有一定的職責&#xff0c;職責指的是類要完成什么樣子的功能&#xff0c;要承擔什么樣子的義務。一個類可以有多種職責&…

MSYS2+CMake配置C/C++開發環境

目錄一、MSYS2是什么1.1 核心架構與組件??1.1.1 背景介紹1.1.1.1 Cygwin1.1.1.2 MinGW和Mingw-w641.1.1.3MSYS和MSYS21.1.2 技術基礎??1.1.3 多環境支持??1.2 核心功能??1.2.1 類Unix開發環境??1.2.2 開發工具鏈??1.2.3 軟件倉庫與包管理??二、安裝和配置2.1 配置…

Vue 3 + TypeScript:package.json 示例 / 詳細注釋說明

一、示例 / 詳細注釋說明 {// 項目基礎信息"name": "vite-project", // 項目名稱&#xff08;建議使用 kebab-case 格式&#xff09;"private": true, // 標記為私有項目&#xff0c;避免意外發布到 npm"version": "1.0.…

SpatialVLM和SpatialRGPT論文解讀

目錄 一、SpatialVLM 1、概述 2、方法 3、實驗 二、SpatialRGPT 1、概述 2、方法 3、訓練方法 4、實驗 一、SpatialVLM 1、概述 SpatialVLM是最早的依賴傳統VLMs實現3D空間推理能力的論文&#xff0c;在24年1月由DeepMind團隊提出&#xff0c;當時對比的還是GPT4v&am…

理解GPU架構:基礎與關鍵概念

GPU 基礎概述&#xff1a;從圖形渲染到 AI 與高性能計算的核心 Graphics Processing Units&#xff08;GPU&#xff09;已從專用的圖形渲染硬件演進為 AI、科學計算與高性能任務的中堅力量。本文將介紹 GPU 架構的基礎知識&#xff0c;包括其組成部分、內存層次結構&#xff0c…

訂單狀態定時處理(Spring Task 定時任務)

訂單狀態定時處理 如果最后一秒剛好支付了咋辦?如何補償? 需要將支付狀態和訂單狀態一起考慮,或者直接使用狀態機 Spring Task 是Spring框架提供的任務調度工具,可以按照約定的時間自動執行某個代碼邏輯。 **定位:**定時任務框架 **作用:**定時自動執行某段Java代碼 …

職得AI簡歷-免費AI簡歷生成工具

本文轉載自&#xff1a;職得AI簡歷-免費AI簡歷生成工具 - Hello123工具導航 ** 一、核心功能解析 職得 AI 簡歷是 AI 驅動的智能求職平臺&#xff0c;通過深度學習算法分析百萬優質簡歷數據&#xff0c;提供從簡歷生成到面試準備的全流程服務&#xff0c;顯著提升求職競爭力。…

8.14 機器學習(1)

機器學習基礎一、什么是機器學習定義&#xff1a;讓計算機利用大量數據在特定任務上持續改進性能的過程&#xff0c;可以讓任務完成的更好。機器學習的領域很多。二、機器學習基本術語數據集、樣本、特征&#xff08;屬性&#xff09;、屬性空間、向量表示、訓練集&#xff08;…

給電腦升級內存,自檢太慢,以為出錯

公司電腦是16G內存&#xff0c;用虛擬機時非常吃力。于是跟領導說&#xff0c;買了32G內存和1T SSD。電腦有兩個SATA數據線&#xff0c;SATA電源頭只有一個。于是買了幾個1轉2&#xff0c;順利接上。把原來的16G拔下&#xff0c;換上32G內存。結果開機沒反應。心里就有點嘀咕&a…

Effective C++ 條款43:學習處理模板化基類內的名稱

Effective C 條款43&#xff1a;學習處理模板化基類內的名稱核心思想&#xff1a;模板化基類&#xff08;templatized base classes&#xff09;中的名稱在派生類模板中默認不可見&#xff0c;需要通過this->前綴、using聲明或顯式基類限定來引入。這是因為編譯器在解析模板…

Mybatis簡單練習注解sql和配置文件sql+注解形式加載+配置文件加載

項目結構 d:\test\runjar\data\static\data\mybatis_helloworld\Mybatis\ ├── lib\ │ ├── asm-3.3.1.jar │ ├── c3p0-0.9.1.2.jar │ ├── cglib-2.2.2.jar │ ├── commons-logging-1.1.1.jar │ ├── ehcache-core-2.6.8.jar │ ├── javassi…

抗日勝利80周年 | HTML頁面

飛翔的和平鴿&#xff1b;屹立的人民英雄紀念碑&#xff1b;倒下的日本國旗&#xff1b;旋轉的金色勛章無不代表著我們勝利了&#xff01;&#xff01;&#xff01;HTML源代碼&#xff1a; <!DOCTYPE html> <html lang"zh-CN"> <head><meta cha…

web仿寫網站

一、完成自己學習的官網&#xff0c;至少三個不同的頁面。1、界面1&#xff08;1&#xff09;代碼<!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-wid…

基于element-plus和IndexedDB數據庫的基礎表單

本文介紹了基于Vue 3和Element Plus的表單項目配置頁面實現。頁面包含搜索欄、操作按鈕、數據表格和分頁組件&#xff0c;使用IndexedDB進行本地數據存儲。主要功能包括&#xff1a;1) 通過模糊查詢搜索項目&#xff1b;2) 分頁顯示項目數據&#xff1b;3) 添加/編輯/刪除項目操…

paimon實時數據湖教程-主鍵表更新機制

在上一章&#xff0c;我們學習了 Paimon 如何保證每一次寫入的原子性和一致性。但數據倉庫的核心需求不僅是寫入&#xff0c;更重要的是更新。想象一個場景&#xff1a;我們需要實時更新用戶的最新信息&#xff0c;或者實時累加計算用戶的消費總額。傳統的 Hive 數據湖對此無能…

第十六屆藍橋杯青少組C++省賽[2025.8.9]第二部分編程題(4、矩陣圈層交錯旋轉)

參考程序&#xff1a;#include <bits/stdc.h> using namespace std;const int MAXN 105; int a[MAXN][MAXN];int main() {int n;if (!(cin >> n)) return 0;for (int i 0; i < n; i)for (int j 0; j < n; j)cin >> a[i][j];int layers n / 2; // 每…