[Tutor] understanding the behavious of parameter 'key' in sort

Shashwat Anand anand.shashwat at gmail.com
Tue Nov 24 03:15:25 CET 2009


I intended to sort a list which sorts according to user-defined custom
sorting-order.
For example: If sorting-order is "zabc...wxy", then the output will be in
lexicographically sorted order but z will always be given priority over rest
others.
as a test case i took sorting order as reverse of normal sorting, hence i
defined user_key as string.ascii_lowercase. It should sort in reverse manner
but I'm not getting expected output.
(Even though it could have just been sorted as reverse=True, but my
intention is to generalize it for this is just a test-case). I'm not able to
find where the bug lies nor am i exactly sure how the key function works,
even though i use it in a regular fashion. Can you guys help me out ?

here is my code:

import string

def userdef_sort(l, user_key):
    tr = string.maketrans("".join(sorted(user_key)), user_key)
    return [i for i in sorted(l, key = lambda x:x.translate(tr), reverse =
False)]

#user_key = raw_input()
user_key = string.ascii_lowercase[::-1]
l = ['a', 'aa', 'ab', 'abc', 'cba', 'cab']

print userdef_sort(l, user_key)

my output: ['cba', 'cab', 'a', 'ab', 'abc', 'aa']
expected output: ['cba', 'cab', 'abc', 'ab', 'aa', 'a']
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091124/e0f5a437/attachment.htm>


More information about the Tutor mailing list