python - 按多个属性分组对象
问题描述
我有一个对象列表,我想根据两个属性对它们进行分组。每个“动作”对象都有一个“任务”和“日期”属性,我想为每个任务/日期组合创建一个“聚合”对象,聚合适合该条件的每个“动作”。
但是,我相信我的代码效率低下,我认为也许某种 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 ..
我应该在这里改变什么?
解决方案
你的问题让我很困惑,但这是你想要的吗?
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)
如果您想要类的名称,请注意,当您将对象添加到列表时,您需要在制作该对象时传入名称
推荐阅读
- angular - 如何修复 SharePoint 中单页 Angular 6 应用程序的 404 Not Found 刷新错误
- python - 使用 BeautifulSoup 使用它包含的文本查找标签
- c# - 为什么 WebClient.DownloadString 没有从网站获取所有 HTML 文本?
- eclipse - 使用 Eclipse 的 JDT,我如何识别项目的类路径?
- excel-formula - MEDIANIF 使用 CSE 并且需要 INDIRECT
- maven - IntelliJ - 什么表明模块正在以 POM 中指示的 Java 版本编译
- sql - 在我的程序的不同块中使用 CTE 的结果
- lilypond - 如何将 midi 导出集成到现有的 lilypond 分数中
- azure-api-management - 在没有订阅密钥的 Azure API 管理中定义请求限制
- javascript - 如何根据 geoJson 功能对每个集群进行不同的着色?