best Pythonic way to do this sort: Python newb

Sean Berry sean at buildingonline.com
Mon Oct 10 01:04:19 EDT 2005


"Paul Rubin" <http://phr.cx@NOSPAM.invalid> wrote in message 
news:7xbr1y9e1c.fsf at ruckus.brouhaha.com...
> "Sean Berry" <sean at buildingonline.com> writes:
>> myList = [[value1, value2, value3],[value1, value2, value3], ...]
>>
>> I have a function which takes value3 from the lists above and returns
>> another value.  I want to use this returned value to sort the lists.
>>
>> So, my resultant list would be ordered by the return value of the
>> function with value3 as its argument.
>>
>> From a relative Python newb, what is the best way to do this?
>
> def get_key(x): return x[2]
> sorted_list = sorted(myList, key=get_key)

Sorry if I am missing something.  But. what is sorted here?

My simplified function looks like this

def myFunction( myNumber ):
    "do some math calculations to myNumber"
    return "result of calculations"

So, I want to sort myList by the return of myFunction( value3 )

I tried doing the following... with no luck so far
myList.sort(lambda x, y: cmp(myFunction(x[2]), myFunction(y[2]))

Thanks for any help.





More information about the Python-list mailing list