1 Replies - 431 Views - Last Post: 27 November 2012 - 02:05 PM Rate Topic: -----

#1 hisan  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 27-November 12

sort list of String without considering Special characters and case

Posted 27 November 2012 - 10:38 AM

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

Is This A Good Question/Topic? 0
  • +

Replies To: sort list of String without considering Special characters and case

#2 Nallo  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 163
  • View blog
  • Posts: 255
  • Joined: 19-July 09

Re: sort list of String without considering Special characters and case

Posted 27 November 2012 - 02:05 PM

I am not sure exactly how you want to order your strings. But list.sort has an optional argument key, that lets you specify how the ordering should go. It takes a function as an argument and sorts the list elements the same way the returned elements would be sorted.

#example
>>> li = [-5, 1, -6, 9]
>>> li.sort(key=abs)
>>> li
[1, -5, -6, 9]



In your case (I assume you want lexicographic ordering) you might want to write a function remove_special that removes the special chars from a string.
def remove_special(s):
    #your code here

list1.sort(key=remove_special)


Was This Post Helpful? 1
  • +
  • -

Page 1 of 1