Oddity using sorted with key
emile at fenx.com
Tue Mar 11 17:23:57 CET 2014
On 03/11/2014 09:13 AM, Josh English wrote:
> I am running into a strange behavior using the sorted function in Python 2.7. The key parameter is not behaving as the docs say it does:
> Here is a snippet of code, simplified from my full program:
> #begin code
> class Thing(object):
> def __init__(self, name):
> self.name = name
> def __repr__(self):
> return "Thing %s" % self.name
> stuff = [Thing('a'), Thing('C'), Thing('b'), Thing('2')]
> more_stuff = [Thing('d'), Thing('f')]
> all_the_stuff = stuff + more_stuff
> print list(sorted(all_the_stuff, key=lambda x: x.name.lower))
in this case everything sorts by the same value of the bound method of
name.lower. You could have used "".lower, which has the same value as
x.name.lower, and gotten the same results.
> print list(sorted(all_the_stuff, key=lambda x: x.name.lower()))
in this case you're sorting by the lower case value of x.name, which is
what you want.
> # END
> The output is:
> [Thing d, Thing f, Thing 2, Thing a, Thing b, Thing C]
> [Thing 2, Thing a, Thing b, Thing C, Thing d, Thing f]
> The second call to sorted works as expected. Just using the method doesn't sort properly.
> Any ideas why I'm seeing two different results? Especially as the correct form is giving me the wrong results?
> Josh English
More information about the Python-list