Python每日一練0010

問題

你有一個字典或者實例的序列,而後你想根據某個特定的字段來分組迭代訪問。python

解決方案

使用itertools.groupby() 函數微信

假設有下列的字典列表:函數

rows = [
    {'address': '5412 N CLARK', 'date': '07/01/2012'},
    {'address': '5148 N CLARK', 'date': '07/04/2012'},
    {'address': '5800 E 58TH', 'date': '07/02/2012'},
    {'address': '2122 N CLARK', 'date': '07/03/2012'},
    {'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'},
    {'address': '1060 W ADDISON', 'date': '07/02/2012'},
    {'address': '4801 N BROADWAY', 'date': '07/01/2012'},
    {'address': '1039 W GRANVILLE', 'date': '07/04/2012'},
]

如今按照date字段來分組訪問,就能夠使用itertools.groupby()spa

from itertools import groupby
from operator import itemgetter
rows.sort(key=itemgetter('date'))
for key, group in groupby(rows, key=itemgetter('date')):
    print(key)
    for item in group:
        print(4 * ' ', item)

輸出code

07/01/2012
     {'address': '5412 N CLARK', 'date': '07/01/2012'}
     {'address': '4801 N BROADWAY', 'date': '07/01/2012'}
07/02/2012
     {'address': '5800 E 58TH', 'date': '07/02/2012'}
     {'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'}
     {'address': '1060 W ADDISON', 'date': '07/02/2012'}
07/03/2012
     {'address': '2122 N CLARK', 'date': '07/03/2012'}
07/04/2012
     {'address': '5148 N CLARK', 'date': '07/04/2012'}
     {'address': '1039 W GRANVILLE', 'date': '07/04/2012'}

討論

itertools.groupby迭代器和一個可選的key參數,按key來分組的,若是key是None的話,則按元素分組對象

itertools.groupby返回每一個不一樣的key和一個迭代器對象,這個迭代器對象就是key對應的一組元素rem

而且itertools.groupby要求分組以前,迭代器的全部元素必須是有序的,緣由跟itertools.groupby的實現有關get

itertools.groupby()大體實現:it

class groupby:
    # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
    # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
    def __init__(self, iterable, key=None):
        if key is None:
            key = lambda x: x
        self.keyfunc = key
        self.it = iter(iterable)
        self.tgtkey = self.currkey = self.currvalue = object()
    def __iter__(self):
        return self
    def __next__(self):
        while self.currkey == self.tgtkey:
            self.currvalue = next(self.it)    # Exit on StopIteration
            self.currkey = self.keyfunc(self.currvalue)
        self.tgtkey = self.currkey
        return (self.currkey, self._grouper(self.tgtkey))
    def _grouper(self, tgtkey):
        while self.currkey == tgtkey:
            yield self.currvalue
            try:
                self.currvalue = next(self.it)
            except StopIteration:
                return
            self.currkey = self.keyfunc(self.currvalue)

來源

Python Cookbookio

關注

歡迎關注個人微信公衆號:python每日一練

相關文章
相關標籤/搜索