0

Suppose I have a class named Fish. now I would ask for a user input to give the name and the size of the fish. now, How can I sort those input values by the size attribute(in decreasing order) and then the name attribute(alphabetically)?

class Fish:
   def __init__(self, size, name):
        self.size:int = int(size)
        self.name:str = name
        pass

def main():
   t = input()

   

for example the user input the following:

d 3
a 1
c 2 
b 1

after the sorting it should be: (it sorted first by the sizes then if the sizes are the same it sorted by the names)

d 3
c 2
a 1
b 1
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • It depends on the way you are storing these objects. If you are using databases, arrays, etc. – Filipizaum Nov 22 '22 at 16:12
  • 1
    `sorted()` takes a `key` argument, which is a reference to a function that it should use to determine the sorting-order of items it's trying to sort. That way you could either create a `lambda`-function or a real function to give to it. – Hampus Larsson Nov 22 '22 at 16:15
  • See this part of the [Sorting HOW TO](https://docs.python.org/3/howto/sorting.html#sort-stability-and-complex-sorts) page in the documentation for more inspiration! – Hampus Larsson Nov 22 '22 at 16:17
  • Does this answer your question? [How to sort a list of objects based on an attribute of the objects?](https://stackoverflow.com/questions/403421/how-to-sort-a-list-of-objects-based-on-an-attribute-of-the-objects) You can specify a `key` argument to `sort`/`sorted`, or define the comparison operators for the class. In either case, you can consider as many attributes as you like to define the comparison or the key. – Pranav Hosangadi Nov 22 '22 at 22:28

1 Answers1

1

In order to override or declare sorting for an object, you should override the comparison operators. You need to specify one of (=, !=) and one of (>, <).

class Fish:
   def __init__(self, size, name):
        self.size = int(size)
        self.name = name

   def __eq__(self,other):
        return self.size == other.size and self.name==other.name

   def __gt__(self,other):
        if self.size != other.size:
            return self.size > other.size
        else:
            return self.name < other.name

An example

f1 = Fish(1,"a")
f2 = Fish(3,'d')
f3 = Fish(2,'c')
f4 = Fish(1,'b')
fishes = [f1,f2,f3,f4]
for fish in sorted(fishes, reverse = True):
    print(fish.name, fish.size)

Output:

d 3
c 2
a 1
b 1
StonedTensor
  • 610
  • 5
  • 19