首页 > 解决方案 > 如何根据连续属性对类的对象进行分组?

问题描述

我们有一个班班:

class Shift:
    def __init__(self, station, week, dayofweek, date):
        self.station = station
        self.week = week
        self.dayofweek = dayofweek
        self.date = date

我们有一个此类实例的排序列表(按这些班次的“日期”)。我想将那些具有连续日期的班次分组在一起,并将这些组存储在最后的列表中。

输入: [Shift(date=1),Shift(date=2),Shift(date=4),Shift(date=5),Shift(date=6)]

输出:[[Shift(date=1),Shift(date=2)],[Shift(date=4),Shift(date=5),Shift(date=6)]]

标签: pythonpython-3.x

解决方案


您需要跟踪上次Shift看到的内容,然后决定是将下一个添加到最后一个组还是开始一个新组。这是一个配对的版本:

class Shift:
    def __init__(self, date):
        self.date = date

    # some helpers to make other code clearer
    # and direct comparisons possible
    def __repr__(self):
        return f"Shift({self.date})"

    def __lt__(self, other):
        return self.date < other.date

    def __sub__(self, other):
        return self.date - other.date

l = [Shift(1),Shift(6),Shift(5),Shift(4),Shift(2),Shift(9),Shift(7), Shift(0)] 

def groupNear(l):
    if not l:
        return l
    group = []
    current = l[0]

    for s in sorted(l):
        if s - current <= 1:
            group.append(s)
        else:
            yield group
            group = [s]
        current = s 
    yield group

list(groupNear(l))

输出:

[[Shift(0), Shift(1), Shift(2)],
 [Shift(4), Shift(5), Shift(6), Shift(7)],
 [Shift(9)]]

推荐阅读