Currently Python sort()
and sorted()
gives me this:
>>> sorted(a, reverse=True, key=lambda s: re.sub('[\[\]]', '', s).lower())
[u'Category123', u'[Cat@123]', u'CAT']
But I need:
[u'[Cat@123]', u'Category123', u'CAT']
I want characters like: !@#$%^&*
can be sorted as bigger than alphabetical chars.
Thanks.
EDIT: Aside from the accepted answer, I figured out this would solve my problem:
>>> sorted(a, reverse=True, key=lambda s:s.upper())
[u'[Cat@123]', u'Category123', u'CAT']
Using sorted() with reduce() to sort letters of string alphabetically. Another alternative is to use reduce() method. It applies a join function on the sorted list using '+' operator.
Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.
The sort() method sorts the list ascending by default. You can also make a function to decide the sorting criteria(s).
Return two values from the key
function, first one is going to be boolean checking whether any of the special characters exists in the string or not and second one the substituted string itself.
>>> def func(s):
subbed = re.sub('[\[\]]', '', s).lower()
return any(c in '!@#$%^&*' for c in s), subbed
...
>>> lst = [u'Category123', u'[Cat@123]', u'CAT']
>>> sorted(lst, reverse=True, key=func)
[u'[Cat@123]', u'Category123', u'CAT']
So, essentially we are sorting something like this:
>>> new_lst = [(False, 'category123'), (True, 'cat@123'), (False, 'cat')]
>>> sorted(new_lst, reverse=True)
[(True, 'cat@123'), (False, 'category123'), (False, 'cat')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With