How to sort a list of strings in reverse order without using reverse=True parameter?

前端 未结 3 1657
面向向阳花
面向向阳花 2020-12-21 08:19

I want to sort a list of strings in reverse order, e.g.:

my_list = [\'aaa\', \'bbb\', \'ccc\']

expected result:

[\'ccc\', \         


        
3条回答
  •  感情败类
    2020-12-21 08:37

    You can do a negative ord on the value and that would work for an ascii string:

    >>> sorted(my_list2, key=lambda x: ([-ord(l) for l in x[0]], x[1]))
    [('bbb', 'aaa'), ('bbb', 'ccc'), ('aaa', 'bbb'), ('aaa', 'ccc')]
    

    For non-ascii though you'd have choices in how you'd want to sort though:

    >>> sorted(my_list2, key=lambda x: ([-ord(l) for l in x[0]], x[1]))
    [('ébb', 'écc'), ('bbb', 'aaa'), ('aaa', 'bbb'), ('aaa', 'ccc')]
    

提交回复
热议问题