Please let me know how to sort the list of String in either ascending / descending order without considering special characters and case.
ex:
list1=['test1_two','testOne','testTwo','test_one']
Applying the list.sort /sorted method results in sorted list
['test1_two', 'testOne', 'testTwo', 'test_one']
but the without considering the special characters and case it should be
['testOne','test_one', 'test1_two','testTwo'] OR
['test_one','testOne','testTwo', 'test1_two' ]
list.sort /sorted method sorts based on the ascii value of the characters but Please let me knwo how do i achieve my expected one
If by special chars you mean "everything that is not letters":
sorted(list1, key=lambda x: re.sub('[^A-Za-z]+', '', x).lower())
It depends on what you mean by "special" characters - but whatever your
definition, the easiest way to do this is to define a key
function.
If you only care about letters:
from string import letters, digits
def alpha_key(text):
"""Return a key based on letters in `text`."""
return [c.lower() for c in text if c in letters]
>>> sorted(list1, key=alpha_key)
['testOne', 'test_one', 'test1_two', 'testTwo']
If you care about digits as well:
def alphanumeric_key(text):
"""Return a key based on letters and digits in `text`."""
return [c.lower() for c in text if c in letters + digits]
>>> sorted(list1, key=alphanumeric_key)
['test1_two', 'testOne', 'test_one', 'testTwo']
If you care about letters and digits and you want digits to sort after letters (which looks like it might be the case from your example output):
def alphanum_swap_key(text):
"""Return a key based on letters and digits, with digits after letters."""
return [ord(c.lower()) % 75 for c in text if c in letters + digits]
>>> sorted(list1, key=alphanum_swap_key)
['testOne', 'test_one', 'testTwo', 'test1_two']
This last one takes advantage of the fact that "z" comes 74 places after "0" in ASCII.
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