0

Using min() in python

if I have a class: class Number: self.weight = x and a list: list =[ a, b, c] and each element in a list has a weight in class, how do I use min to get the lowest element from the list according to its self. weight I tried doing this: lowest = min(list, key = self. weight) but that didn't work

23rd Jul 2021, 10:01 AM
Kirill
Kirill - avatar
7 ответов
+ 1
That's not the right way to initialize a class property. Try this class Number: def __init__(self, w): self.weight = w
23rd Jul 2021, 10:14 AM
Baribor Saturday
Baribor Saturday - avatar
+ 1
If I correctly understood your question I think you should use a syntax like below: lowest = min([Number_class_instance1.weight,Number_class_instance2.weight,Number_class_instance3.weight])
23rd Jul 2021, 10:17 AM
Abolfazl Dahaghayn
Abolfazl Dahaghayn - avatar
+ 1
Okay. If the items in the list are all Number objects, you can add a magic method to the class: def __gt__(self, other): return self.weight > other.weight So you can just call, max(list) and get the greatest
23rd Jul 2021, 10:23 AM
Baribor Saturday
Baribor Saturday - avatar
+ 1
for minimum add: def __lt__(self, other): return self.weight < other.weight
23rd Jul 2021, 10:25 AM
Baribor Saturday
Baribor Saturday - avatar
+ 1
Consider that you've a list of Number class instances (for example named as "instances") that you don't know the length of that list now and in future. You can use something like this: lowest= min([ i.weight for i in instances])
23rd Jul 2021, 10:27 AM
Abolfazl Dahaghayn
Abolfazl Dahaghayn - avatar
0
✔✅Barry🔧 i know, I was just too lazy to type it on my phone so I just used the quick way cause everyone understands anyways
23rd Jul 2021, 10:19 AM
Kirill
Kirill - avatar
0
ɧოɧ but what if we don't know how much elements are there in the list
23rd Jul 2021, 10:21 AM
Kirill
Kirill - avatar