别再用List去重了!Python这个技巧,让代码效率提升10倍
这是一份有基础、有深度的 Python 必备秘籍。
基础
################## 字典 初始化
>>> d1 = {"name": "jason", "age": 20, "gender": "male"}
>>> d2 = dict({'name': 'jason', 'age': 20, 'gender': 'male'})
>>> d3 = dict([('name', 'jason'), ('age', 20), ('gender', 'male')])
>>> d4 = dict(name='jason', age=20, gender='male')
>>> d1 == d2 == d3 == d4
True
################## 集合 初始化
>>> s1 = {1,2,3}
>>> s2 = set([1,2,3])
>>> s1 == s2
True
################## 字典 访问
>>> d1
{'name': 'jason', 'age': 20, 'gender': 'male'}
>>> d1["name"] # 查一个存在的 key
'jason'
>>> d1["location"] # 查一个不存在的 key
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'location'
>>> d1.get("location", "null") # 查一个不存在的 key,且指定默认值
'null'
################## 字典 判断包含关系
>>> d1
{'name': 'jason', 'age': 20, 'gender': 'male'}
>>> "name" in d1
True
>>> "location" in d1
False
################## 集合 判断包含关系
>>> s1
{1, 2, 3}
>>> 1 in s1
True
>>> 10 in s1
False
################## 字典 增加、删除、更新
>>> d1
{'name': 'jason', 'age': 20, 'gender': 'male'}
>>> d1["gender"]
'male'
>>> d1["dob"] = "1999-02-20" # 更新
>>> d1
{'name': 'jason', 'age': 20, 'gender': 'male', 'dob': '1999-02-20'}
>>> d1.pop("dob") # get 并 del
'1999-02-21'
>>> d1
{'name': 'jason', 'age': 20, 'gender': 'male'}
################## 集合 增加、删除、更新
>>> s1
{1, 2, 3}
>>> s1.add(4) # 增加
>>> s1
{1, 2, 3, 4}
>>> s1.remove(3) # 删除
>>> s1
{1, 2, 4}
################## 字典 排序
>>> d1 = {"b": 1, "a": 2, "c": 3}
>>> d_sorted_by_key = sorted(d1.items(), key=lambda x:x[0]) # 按 key 排序,并返回
>>> d_sorted_by_value = sorted(d1.items(), key=lambda x:x[1]) # 按 value 排序,并返回
>>> d_sorted_by_key
[('a', 2), ('b', 1), ('c', 3)]
>>> d_sorted_by_value
[('b', 1), ('a', 2), ('c', 3)]
################## 集合 排序
>>> s1 = {3,2,4,1}
>>> sorted(s1) # 排序,并返回
[1, 2, 3, 4]
操作差异
- 集合不支持索引操作,因为,集合本质上是一个哈希表。
性能差异
- 字典 和 集合 都是性能高度优化的数据结构,按需选择就好。
集合 vs 列表
###################################
# 结论:
# 在去重的需求场景下,集合性能 > 列表性能
###################################
# 示例需求:找出这些商品有多少种不同的价格
# list version
def find_unique_price_using_list(products):
unique_price_list = []
for _, price in products: # A
if price not in unique_price_list: #B
unique_price_list.append(price)
return len(unique_price_list)
# set version
def find_unique_price_using_set(products):
unique_price_set = set()
for _, price in products:
unique_price_set.add(price)
return len(unique_price_set)
# 初始化测试数据
id = [x for x in range(0, 100000)]
price = [x for x in range(200000, 300000)]
products = list(zip(id, price))
# 列表版本的时间
start_using_list = time.perf_counter()
find_unique_price_using_list(products)
end_using_list = time.perf_counter()
print("time elapse using list: {}".format(end_using_list - start_using_list))
# 输出: time elapse using list: 41.61519479751587
# 集合版本的时间
start_using_set = time.perf_counter()
find_unique_price_using_set(products)
end_using_set = time.perf_counter()
print("time elapse using set: {}".format(end_using_set - start_using_set))
# 输出: time elapse using set: 0.008238077163696289
存储差异
-
字典 和 集合 的内部都是一张哈希表。
-
对于字典来说,这张哈希表,存储了哈希值、键、值,这 3 个元素。
-
对于集合来说,这张哈希表,只存储了哈希值、键,这 2 个元素。
-
老版本 Python 的哈希表结构如下:
-
-
新版 Python,哈希表会把 索引、哈希值、键、值单独分开
####################### 存储结构
Indices(哈希槽)
----------------------------------------------------
None | index | None | None | index | None | index ...
----------------------------------------------------
Entries
--------------------
hash0 key0 value0
---------------------
hash1 key1 value1
---------------------
hash2 key2 value2
---------------------
...
---------------------
####################### 存储形式
indices = [None, 1, None, None, 0, None, 2]
entries = [
[1231236123, 'name', 'mike'],
[-230273521, 'dob', '1999-01-01'],
[9371539127, 'gender', 'male']
]
总结
- 字典在 Python3.7+ 确定为有序的数据结构,相对于列表和元组,字典的性能更优。
- 集合是一系列无序的、唯一的元素组合。
- 字典和集合通常运用在对元素的高效查找、去重等场景。
-------- 写在最后 --------
我的公众号正在连载《FastAPI 开发实战》、《Python 核心技术》、《Python 自动化办公》《职场》。
关注我,每天解锁一个实用知识点。
点赞 :如果觉得有收获,点赞支持一下吧!
分享 :分享给身边同样对Python感兴趣的朋友!
关注我 :不要错过每一篇 Python 实战内容!
每周更新 Python 核心技术、FastAPI 开发实战、Python 自动化办公、职场等硬核技巧,助你成为 10 倍效率的开发者!
#Python #FastAPI #API #Web开发 #程序员 #编程教程 #效率提升