Python---多字段排序,列表套字典,字典的排序,分組,itemgetter多字段排序

from operator import itemgetter
# Key使用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'}]

  分組,排序

from itertools import groupby
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'))
for k, item in groupby(a, key=itemgetter('weather')):
    print(k)
    # print(item)
    for i in item:
        print(i)
==================================================
cloud
{'date': '2019-12-14', 'weather': 'cloud'}
{'date': '2019-12-15', 'weather': 'cloud'}
sunny
{'date': '2019-12-13', 'weather': 'sunny'}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章