哈希表(Hash Table / Dictionary)基础知识
作者:野牛程序员:2025-12-22 11:37:09python阅读 2094
哈希表(Hash Table / Dictionary)基础知识
# /*
# 哈希表(Hash Table / Dictionary)基础知识
# --------------------------------------------------------
# 定义:
# 哈希表是一种通过哈希函数将键映射到存储位置的数据结构,
# 允许快速的插入、查找和删除操作。
#
# 特点:
# - 平均时间复杂度 O(1)(查找/插入/删除)
# - 键必须唯一
# - 常用于计数、映射关系、去重等场景
#
# Python 内置 dict 即为哈希表实现
# */
# --------------------------------------------------------
# 哈希表的基本操作
hash_table = {}
# 插入 / 更新
hash_table["apple"] = 3
hash_table["banana"] = 5
hash_table["orange"] = 2
print("哈希表内容:", hash_table)
# 查找
print("apple 对应的值:", hash_table.get("apple"))
# 删除
del hash_table["orange"]
print("删除 orange 后的哈希表:", hash_table)
# 遍历
print("遍历哈希表:")
for key, value in hash_table.items():
print(key, "->", value)
# --------------------------------------------------------
# 示例:统计列表中元素出现次数
fruits = ["apple", "banana", "apple", "orange", "banana", "apple"]
count_dict = {}
for fruit in fruits:
count_dict[fruit] = count_dict.get(fruit, 0) + 1
print("元素出现次数统计:", count_dict)
# --------------------------------------------------------
# 要点总结:
# 1) 哈希表通过键快速访问值;
# 2) Python dict 是典型哈希表实现,键唯一、值可重复;
# 3) 常用操作:插入、查找、删除、遍历;
# 4) 可用于计数、映射、缓存、去重等场景;
# 5) 时间复杂度:平均 O(1),最坏 O(n)(哈希冲突严重时)。
# */
#
# 哈希表内容: {'apple': 3, 'banana': 5, 'orange': 2}
# apple 对应的值: 3
# 删除 orange 后的哈希表: {'apple': 3, 'banana': 5}
# 遍历哈希表:
# apple -> 3
# banana -> 5
# 元素出现次数统计: {'apple': 3, 'banana': 2, 'orange': 1}野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:双端队列(Deque)
- 下一篇:图(Graph)简单表示
