where or filter on list
Duncan Booth
duncan.booth at invalid.invalid
Wed Aug 30 09:50:17 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]
>
> 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().
You're not the only one who has trouble remembering just what is in each
version.
> 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).
And for Python 2.5 users only we have the exciting new option of:
>>> foo = [5, 2, -1, -7, 3, -6, 2, 12]
>>> min(foo, key=abs)
-1
More information about the Python-list
mailing list