跳转至

🔥AI副业赚钱星球

点击下面图片查看

郭震AI
@author jackzhenguo
@desc 
@date 2019/12/19

131 itemgetter和key函数

注意到sortgroupby所用的key函数,除了lambda写法外,还有一种简写,就是使用itemgetter

a = [{'date': '2019-12-15', 'weather': 'cloud'},
 {'date': '2019-12-13', 'weather': 'sunny'},
 {'date': '2019-12-14', 'weather': 'cloud'}]
from operator import itemgetter
from itertools import groupby

a.sort(key=itemgetter('weather'))
for k, items in groupby(a, key=itemgetter('weather')):
     print(k)
     for i in items:
         print(i)

结果:

cloud
{'date': '2019-12-15', 'weather': 'cloud'}
{'date': '2019-12-14', 'weather': 'cloud'}
sunny
{'date': '2019-12-13', 'weather': 'sunny'}

上一个例子 下一个例子

大家在看

京ICP备20031037号-1 | AI之家 | AI资讯 | Python200 | 数据分析