where or filter on list

skip at pobox.com skip at pobox.com
Wed Aug 30 09:31:03 EDT 2006


    >> Another way might be to sort by absolute value:
    >> 
    >> intermed = [(abs(v), v) for v in foo]
    >> intermed.sort()
    >> intermed[0][1]

    Duncan> It is slightly simpler if you use sorted (assuming a recent
    Duncan> enough Python):

    Duncan>     intermed = sorted(foo, key=abs)
    Duncan>     print intermed[0]

Yeah, sorted() is new enough that my brain generally doesn't realize it's
available.  I also never remember the key parameter to list.sort().  Now
that you mention it:

    >>> foo = [5, 2, -1, -7, 3, -6, 2, 12]
    >>> foo.sort(key=abs)
    >>> foo
    [-1, 2, 2, 3, 5, -6, -7, 12]

(assuming you don't mind reording the list - if you do, then sorted() is
your friend).

Skip



More information about the Python-list mailing list