Oddity using sorted with key

Chris Kaynor ckaynor at zindagigames.com
Tue Mar 11 12:20:43 EDT 2014


On Tue, Mar 11, 2014 at 9:13 AM, Josh English <Joshua.R.English at gmail.com>wrote:

> print list(sorted(all_the_stuff, key=lambda x: x.name.lower))
>

In this case, the key being sorted on is the function object x.name.lower,
not the result of the call.

It might make more sense if you break the lambda out into a separate def
statement, like this:
def myKeyFunc(x):
    return x.name.lower # Return the function that produces the lower-cased
name.
print list(sorted(all_the_stuff, key=myKeyFunc))



>  print list(sorted(all_the_stuff, key=lambda x: x.name.lower()))
>

In this case, you are calling x.name.lower, and the key being used is the
result of that call.

And heres what this one looks like broken down:
def myKeyFunc(x):
    return x.name.lower() # Return the lower-cased name.
print list(sorted(all_the_stuff, key=myKeyFunc))

Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140311/4b9e9e67/attachment.html>


More information about the Python-list mailing list