Group consecutive dates together with Python

前端 未结 1 509
灰色年华
灰色年华 2021-02-11 05:58

Given:

dates = [
  datetime(2014, 10, 11), 

  datetime(2014, 10, 1), 
  datetime(2014, 10, 2),
  datetime(2014, 10, 3),

  datetime(2014, 10, 5         


        
相关标签:
1条回答
  • 2021-02-11 06:22

    I like itertools:

    from itertools import tee, zip_longest
    from datetime import datetime, timedelta
    
    one_day = timedelta(days=1)
    
    def pairwise(iterable):
        a, b = tee(iterable)
        next(b, None)
        return zip_longest(a, b, fillvalue=None)
    
    def collapse_ranges(sorted_iterable, inc):
        pairs = pairwise(sorted_iterable)
        for start, tmp in pairs:
            if inc(start) == tmp:
                for end, tmp in pairs:
                    if inc(end) != tmp:
                        break
                yield start, end
            else:
                yield start
    
    # dates = [...]
    
    numbers = [11, 1, 2, 3, 5, 5, 6, 22, 20, 21, 9, 7, 6]
    
    if __name__ == '__main__':
        import pprint
        for each in collapse_ranges(sorted(set(dates)), lambda d: d + one_day):
            pprint.pprint(each)
        for each in collapse_ranges(sorted(set(numbers)), (1).__add__):
            pprint.pprint(each)
    

    Result:

    (datetime.datetime(2014, 10, 1, 0, 0), datetime.datetime(2014, 10, 3, 0, 0))
    (datetime.datetime(2014, 10, 5, 0, 0), datetime.datetime(2014, 10, 7, 0, 0))
    datetime.datetime(2014, 10, 9, 0, 0)
    datetime.datetime(2014, 10, 11, 0, 0)
    (datetime.datetime(2014, 10, 20, 0, 0), datetime.datetime(2014, 10, 22, 0, 0))
    (1, 3)
    (5, 7)
    9
    11
    (20, 22)
    
    0 讨论(0)
提交回复
热议问题