Simple questions on use of objects (probably faq)

Delaney, Timothy (Tim) tdelaney at avaya.com
Wed Mar 8 17:53:11 EST 2006


Max M wrote:

> decorated = [(obj.x, obj) for obj in objects]
> max_decorated = max(decorated)
> max_obj = max_decorated[-1]

Python 2.5 will make this even easier - max() and min() aquire a `key`
keyword parameter much like list.sort()/sorted().

    max_obj = max(objects, key=operator.attrgetter('x'))

Also, using your DSU version, you should (nearly) always include the
object index in the tuple so you don't break ties by comparing the
actual objects i.e.

    decorated = [(obj.x, i, obj) for (i, obj) in enumerate(objects)]
    max_decorated = max(decorated)
    max_obj = max_decorated[-1]

Note that this will always return the *last* entry with maximum obj.x as
the max - to return the first one found, use (obj.x, -i, obj).

Tim Delaney



More information about the Python-list mailing list