where or filter on list

Duncan Booth duncan.booth at invalid.invalid
Wed Aug 30 08:58:30 EDT 2006


skip at pobox.com wrote:

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

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

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

The sorted list is of course the best way if you want to find not just one 
value but a group, e.g. the n nearest to 0.

For nearest to a non-zero value v the version with sorted becomes:

   intermed = sorted(foo, key=lambda x:abs(x-v))



More information about the Python-list mailing list