這6個Python進階用法,你用過哪些?
點擊上方藍色字體,關(guān)注程序員zhenguo

1 列表生成式和生成器
from numpy import random
a = random.random(10000)
lst = []
for i in a:
lst.append(i * i) # 不推薦做法
lst = [i * i for i in a] # 使用列表生成式
gen = (i * i for i in a) # 生成器更節(jié)省內(nèi)存
2 字典推導式創(chuàng)建子集
a = {'apple': 5.6, 'orange': 4.7, 'banana': 2.8}
da = {key: value for key, value in a.items() if value > 4.0}
print(da) # {'apple': 5.6, 'orange': 4.7}
3 Key使用itemgetter多字段排序
from operator import itemgetter
a = [{'date': '2019-12-15', 'weather': 'cloud'},
{'date': '2019-12-13', 'weather': 'sunny'},
{'date': '2019-12-14', 'weather': 'cloud'}]
a.sort(key=itemgetter('weather', 'date'))
print(a)
# [{'date': '2019-12-14', 'weather': 'cloud'}, {'date': '2019-12-15', 'weather': 'cloud'}, {'date': '2019-12-13', 'weather': 'sunny'}]
4 Key使用itemgetter分組
from operator import itemgetter
from itertools import groupby
a.sort(key=itemgetter('weather', 'date')) # 必須先排序再分組
for k, items in groupby(a, key=itemgetter('weather')):
print(k)
for i in items:
print(i)
5 sum類聚合函數(shù)與生成器
Python中的聚合類函數(shù)sum,min,max第一個參數(shù)是iterable類型,一般使用方法如下:
a = [4,2,5,1]
sum([i+1for i in a]) # 16
使用列表生成式[i+1 for i in a]創(chuàng)建一個長度與a一樣的臨時列表,這步完成后,再做sum聚合。
試想如果你的數(shù)組a長度是百萬級,再創(chuàng)建一個這樣的臨時列表就很不劃算,最好是一邊算一邊聚合,稍改動為如下:
a = [4,2,5,1]
sum(i+1for i in a) # 16
此時i+1 for i in a是(i+1 for i in a)的簡寫,得到一個生成器(generator)對象,如下所示:
In [8]:(i+1for i in a)
OUT [8]: at 0x000002AC7FFA8CF0>
生成器每迭代一步吐出(yield)一個元素并計算和聚合后,進入下一次迭代,直到終點。
6 ChainMap邏輯上合并多個字典
dic1 = {'x': 1, 'y': 2 }
dic2 = {'y': 3, 'z': 4 }
merged = {**dic1, **dic2} # {'x': 1, 'y': 3, 'z': 4}
修改merged['x']=10,dic1中的x值不變
ChainMap?只在邏輯上合并,在內(nèi)部創(chuàng)建了一個容納這些字典的列表。
from collections import ChainMap
merged = ChainMap(dic1,dic2)
print(merged)
# ChainMap({'x': 1, 'y': 2}, {'y': 3, 'z': 4})
使用ChainMap合并字典,修改merged['x']=10,dic1中的x值改變
對應關(guān)鍵詞下載評論
圖片
表情
