Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn list into list of lists using an object attribute

Tags:

python

I have a list of objects

objects = [<object 1>, <object 2>, <object 3>, <object 4>, <object 5>, <object 5>]

Each object has an attribute date (object.date). I would like to split the list into a list of lists where each sublist has only objects with the same date. Is there some smart way to do this? My naive solution is

list_of_lists = []
for object in objects:
    success = 0
    for list in list_of_lists:
        if object.date == list[0].date:
            list.append(object)
            success = 1
            break
    if not success:
        list_of_lists.append([object])

this does give the correct result, but I am just wondering about an optimal solution.

like image 875
carl Avatar asked Mar 13 '23 17:03

carl


1 Answers

You can use itertools.groupby():

from itertools import groupby
from operator import attrgetter
my_lists = [list(g) for _, g in groupby(sorted(objects, key=attrgetter('date')), attrgetter('date'))]

Note that if your objects are already sorted by the date attribute, you don't need to sort it.

Based on your need, if you need more performance in terms of runtime speed you can use a dictionary for categorizing the objects:

my_dict = {}

for obj in objects:
    my_dict.setdefault(obj.date, []).append(obj) # Don't forget to call the `date` if it's callable

Note, if you just want the lists in a categorized form you can get the dictionary values:

my_lists = my_dict.values()
like image 95
Mazdak Avatar answered Mar 24 '23 22:03

Mazdak