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
7 odpowiedzi
+ 1
That's not the right way to initialize a class property. Try this
class Number:
def __init__(self, w):
self.weight = w
+ 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])
+ 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
+ 1
for minimum add:
def __lt__(self, other):
return self.weight < other.weight
+ 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])
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
0
ɧოɧ but what if we don't know how much elements are there in the list