Python 按多个属性对对象分组

Python 按多个属性对对象分组,python,Python,我有一个对象列表,我想根据两个属性对它们进行分组。 每个“action”对象都有一个“task”和“date”属性,我想为每个task/date组合创建一个“Aggregation”对象,它聚合适合该条件的每个“action” 然而,我相信我的代码效率很低,我想也许某种map-reduce函数在这里会更好?(我真的不知道,我在问) 可复制示例: class Action(): def __init__(self, date, task): self.date = date

我有一个对象列表,我想根据两个属性对它们进行分组。 每个“action”对象都有一个“task”和“date”属性,我想为每个task/date组合创建一个“Aggregation”对象,它聚合适合该条件的每个“action”

然而,我相信我的代码效率很低,我想也许某种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
class Agregation():
    def __init__(self, actions = []):
        self.actions = actions

    # Some methods i will use in the future
可再现的示例输出

expected_result = [ object1 , object2 ]

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

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

我当前的解决方案:

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
class Agregation():
    def __init__(self, actions = []):
        self.actions = actions

    # Some methods i will use in the future
例如,上面的代码是有效的。然而,我认为在“splitDivision”函数上使用嵌套字典并不是真正的pythonic


我应该在这里更改什么?

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

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)


注意:如果您想要类的名称,当您将对象添加到列表中时,您需要在创建该对象时传入名称

您能简化一下吗?可能提供示例输入和预期输出。我同意你的观点,也许有更好的方法来写这篇文章。好的,我现在正在编辑:)我认为最好不要看我的例子…这只是让人困惑。请提供一个答案。你们现在能检查一下吗?我举了个例子。希望这是你在这里使用类的明确原因?似乎您只是在表示一些数据,所以您可以使用
pandas
,它有一个
groupby
方法,具有大量选项…感谢您的努力,但我的问题似乎完全被误解了(我不知道该怎么做才能更好地解释它,但现在看来,我的解决方案已经足够好了。我的意思是,“action”对象的日期/任务值的每个组合都应该自动位于一个单独的聚合“object”中。但无需担心:)我的解释不够简洁,这是我的错。。