0

Im trying figure out if there is a simple way to group a few objects by their variables?

I have tried to loop through the objects, creating seperate sets then again create new objects but I feel like my approaches are way too complicated, is there any common simple way?

class Dog:
  def __init__(self, name, age):
    self.name = name
    self.age = age

dogs = [Dog('Buddy', 3), Dog('Max', 3), Dog('Charlie', 5), 
    Dog('Cooper', 1), Dog('Jack', 3),Dog('Rocky', 4), Dog('Bear', 1), 
    Dog('Duke', 3), Dog('Ace', 5)]


 grouped_dogs = [(Dog('Buddy', 3), Dog('Max', 3), Dog('Duke', 3)), 
     (Dog('Charlie', 5)), (Dog('Cooper', 1), Dog('Bear', 1)), 
     (Dog('Rocky', 4))] # expected output

I wish it could be grupped by age like grouped_dogs in the end.

2 Answers 2

4

You can sort your dogs with key variable and then use groupby function from itertools module:

from itertools import groupby

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return (self.name, self.age)

dogs = [Dog('Buddy', 3), Dog('Max', 3), Dog('Charlie', 5), 
    Dog('Cooper', 1), Dog('Jack', 3),Dog('Rocky', 4), Dog('Bear', 1), 
    Dog('Duke', 3), Dog('Ace', 5)]

sorted_dogs = sorted(dogs, key=lambda x: x.age)

print([(d.name, d.age) for d in sorted(dogs, key=lambda x: x.age)])

for u, v in groupby(sorted_dogs, key=lambda x: x.age):
    print(u, [(d.name, d.age) for d in v])
[('Cooper', 1), ('Bear', 1), ('Buddy', 3), ('Max', 3), ('Jack', 3), ('Duke', 3), ('Rocky', 4), ('Charlie', 5), ('Ace', 5)]


1 [('Cooper', 1), ('Bear', 1)]
3 [('Buddy', 3), ('Max', 3), ('Jack', 3), ('Duke', 3)]
4 [('Rocky', 4)]
5 [('Charlie', 5), ('Ace', 5)]

Sign up to request clarification or add additional context in comments.

Comments

2

You can do it using groupby:

import itertools as it

groups = it.groupby(dogs, key=lambda x: x.age)
grouped_dogs = []

for _, items in groups:
    grouped_dogs.append([(x.name, x.age) for x in items])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.