Skip to content

Latest commit

 

History

History
53 lines (41 loc) · 978 Bytes

129.md

File metadata and controls

53 lines (41 loc) · 978 Bytes
@author jackzhenguo
@desc 
@date 2019/12/3

129 groupby单字段分组

天气记录:

a = [{'date': '2019-12-15', 'weather': 'cloud'},
 {'date': '2019-12-13', 'weather': 'sunny'},
 {'date': '2019-12-14', 'weather': 'cloud'}]

按照天气字段weather分组汇总:

from itertools import groupby
for k, items in  groupby(a,key=lambda x:x['weather']):
     print(k)

输出结果看出,分组失败!原因:分组前必须按照分组字段排序,这个很坑~

cloud
sunny
cloud

修改代码:

a.sort(key=lambda x: x['weather'])
for k, items in  groupby(a,key=lambda x:x['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'}
[上一个例子](128.md) [下一个例子](130.md)