Вы можете сортировать своих собак по переменной key
, а затем использовать функцию groupby из модуля itertools:
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)]