131
编辑日期: 2024-11-28 文章阅读: 次
@author jackzhenguo
@desc
@date 2019/12/19
131 itemgetter和key函数
注意到sort
和groupby
所用的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'}