Jesse Bluestein
Jesse Bluestein

Reputation: 57

Select object with max attribute in list of objects

I have a list of 'nodes' and I'm trying to select the node that has the max value from that list. The following code achieves this, but I think it could be done in a much more elegant way. Is there a nice way to do this with list comprehensions that I'm missing? Thanks in advance!

Example code:

maxVal = 0
for node in self.nodes:
    if node.val > maxVal:
        maxVal = node.val
        self.maxValNode = node
self.maxVal = self.maxValNode.val

Upvotes: 0

Views: 199

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155363

The max function can take a key argument to determine how to compare items.

So a simple self.maxValNode = max(self.nodes, key=lambda node: node.val) performs the same work (aside from your last line, which you'd leave as is). For slightly greater speed (and avoiding unnecessary lambdas, which are a pet peeve of mine), import the operator module beforehand, to allow:

from operator import attrgetter   # Top of file

self.maxValNode = max(self.nodes, key=attrgetter('val'))

Upvotes: 3

Related Questions