Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the max value of attributes from a list of objects

I have this list of objects which have a x and a y parameter (and some other stuff).

path.nodes = (     <GSNode x=535.0 y=0.0 GSLINE GSSHARP>,     <GSNode x=634.0 y=0.0 GSLINE GSSHARP>,     <GSNode x=377.0 y=706.0 GSLINE GSSHARP>,     <GSNode x=279.0 y=706.0 GSLINE GSSHARP>,     <GSNode x=10.0 y=0.0 GSLINE GSSHARP>,     <GSNode x=110.0 y=0.0 GSLINE GSSHARP>,     <GSNode x=189.0 y=216.0 GSLINE GSSHARP>,     <GSNode x=458.0 y=216.0 GSLINE GSSHARP> ) 

I need to have the max y of this list. Though, I tried this:

print(max(path.nodes, key=y)) 

And I get this error:

NameError: name 'y' is not defined 

I am kinda new to Python and the docs give me no clue. I think I am doing wrong with the keyword because if iterate through nodes like this:

for node in path.nodes:     print(node.y) 

I'll get the values of y. Could somebody provide me an explanation?

like image 878
PDXIII Avatar asked Oct 25 '12 11:10

PDXIII


People also ask

How do you find the max value of an attribute in an array object?

Maximum value of an attribute in an array of objects can be searched in two ways, one by traversing the array and the other method is by using the Math. max. apply() method.

How will you get the max valued item of a list?

Use max() to Find Max Value in a List of Strings and Dictionaries. The function max() also provides support for a list of strings and dictionary data types in Python. The function max() will return the largest element, ordered by alphabet, for a list of strings.


1 Answers

To get just the maximum value and not the entire object you can use a generator expression:

print(max(node.y for node in path.nodes)) 
like image 172
Mark Byers Avatar answered Oct 11 '22 06:10

Mark Byers