Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort: How to treat special character greater than alphabetical in Python 2?

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']
like image 510
huygn Avatar asked Jul 25 '15 06:07

huygn


People also ask

How do you arrange a character in a string in alphabetical order in Python?

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.

How do you sort things alphabetically in Python?

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.

How do I sort a list in Python 2?

The sort() method sorts the list ascending by default. You can also make a function to decide the sorting criteria(s).


1 Answers

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')]
like image 106
Ashwini Chaudhary Avatar answered Oct 24 '22 12:10

Ashwini Chaudhary