Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Collaborating with max, min and sort

The min and max functions can interact with our classes in relatively simple ways. Similarly, the sort method of a list can also interact with our new class definitions. In all three cases, a keyword parameter of key can be used to control which attributes are used for determining minimum, maximum or sort order.

The key parameter must be given a function, and that function is evaluated on each item that is being compared. Here's a quick example.

class Boat( object ):
    def __init__( self, name, loa ):
        self.name= name
        self.loa= loa

def byName( aBoat ):
    return aBoat.name

def byLOA( aBoat ):
    return aBoat.loa

fleet = [ Boat("KaDiMa", 18 ), Boat( "Emomo", 21 ), Boat("Leprechaun", 30 ) ]

first= min( fleet, key=byName )
print "Alphabetically First:", first
longest= max( fleet, key=byLOA )
print "Longest:", longest

As min, max or sort traverse the sequence doing comparisons among the objects, they evaluate the key function we provided. In this example, the provided function simply selects an attribute. Clearly the functions could do calculations or other operations on the objects.


 
 
  Published under the terms of the Open Publication License Design by Interspire