首页 > 解决方案 > 按多个属性分组对象

问题描述

我有一个对象列表,我想根据两个属性对它们进行分组。每个“动作”对象都有一个“任务”和“日期”属性,我想为每个任务/日期组合创建一个“聚合”对象,聚合适合该条件的每个“动作”。

但是,我相信我的代码效率低下,我认为也许某种 map reduce 功能在这里会更好?(我真的不知道,我在问)

可重现的例子:

class Action():
    def __init__(self, date, task):
        self.date = date
        self.task = task

action_1 = Action('2020/01/01', '1')
action_2 = Action('2020/01/02', '1')
action_3 = Action('2020/01/01', '1')
action_4 = Action('2020/01/01', '1')

# In reality i'll have a list of multiple actions with multiple date/task values

可重现的示例输出

expected_result = [ object1 , object2 ]

object1.actions = [action1, action3, action4]
object2.actions = [action2]

# Every object can only contain actions with the same date/task

我目前的解决方案:

class Agregation():
    def __init__(self, actions = []):
        self.actions = actions

    # Some methods i will use in the future
def splitDivision(actions):
    result = {}

    for action in actions:
        task = action.task
        date = action.date

        if not date in result:
            result[date] = {}
        if not task in result[date]:
            result[date][task] = Agregation(date, task)

        result[date][task].actions.append(action)

    return list(x for date in result.values() for x in date.values())

例如,上面的代码有效。但是我认为在“splitDivision”函数上使用嵌套字典并不是真正的pythonic ..

我应该在这里改变什么?

标签: python

解决方案


你的问题让我很困惑,但这是你想要的吗?

inst = []
class Action():
    def __init__(self, date, task):
        self.date = date
        self.task = task
        inst.append(self)

action_1 = Action('2020/01/01', '1')
action_2 = Action('2020/01/02', '1')
action_3 = Action('2020/01/01', '1')
action_4 = Action('2020/01/01', '1')


actions_list = list(sorted(set([(x.date,x.task) for x in inst])))
class Agregation():
    def __init__(self, ):
        
        object1_actions = [x for x in inst if (x.date,x.task) == actions_list[0]]
        object2_actions = [x for x in inst if (x.date,x.task) == actions_list[1]]
        
        print(object1_actions)
        print(object2_actions)

如果您想要类的名称,请注意,当您将对象添加到列表时,您需要在制作该对象时传入名称


推荐阅读