2025-09-10:仓库迁移
This commit is contained in:
19
1.数据结构与算法/17.字典子集.py
Normal file
19
1.数据结构与算法/17.字典子集.py
Normal file
@@ -0,0 +1,19 @@
|
||||
# 假如我们有一个字典,需要提取子集:
|
||||
price = {
|
||||
"ACME": 45.23,
|
||||
"AAPL": 612.78,
|
||||
"IBM": 205.55,
|
||||
"HPQ": 37.2,
|
||||
"FB": 10.75
|
||||
}
|
||||
|
||||
# 直接用字典推导式
|
||||
p1 = {key :value for key, value in price.items() if value > 200}
|
||||
|
||||
# 提取key也是
|
||||
keys = {"AAPL", "IBM", "HPQ", "MSFT"}
|
||||
p2 = {key : value for key, value in price.items() if key in keys}
|
||||
|
||||
# 字典推导式是最快的方法,比下面两个办法都快:
|
||||
dict((key, value) for key, value in price if value > 100) # 快两倍
|
||||
{key:price[key] for key in price.keys() if key in price.keys() & keys} # 快1.6倍
|
Reference in New Issue
Block a user