user1170364
user1170364

Reputation: 349

python list sort

I have got a list i.e.

ls= [u'Cancer',u"Men's",u'Orthopedics',u'Pediatric',u"Senior's",u"Women's"]

ls.sort() does not seem to work here due to presence of single quote in the list elements.

I need to sort this list. Any idea???

Upvotes: 0

Views: 12508

Answers (2)

Kimvais
Kimvais

Reputation: 39548

Actually, the question is valid and the answer is not exactly correct in general case. If the test material was not already sorted, it would not get correctly alphabetized but the 's would cause the list to be sorted to wrong order:

>>> l = ["'''b", "a", "a'ab", "aaa"]
>>> l.sort()
>>> l
["'''b", 'a', "a'ab", 'aaa']
>>> from functools import partial
>>> import string
>>> keyfunc = partial(string.replace, old="'", new="")
>>> l.sort(key=keyfunc)
>>> l
['a', 'aaa', "a'ab", "'''b"]

Upvotes: 5

Eli Bendersky
Eli Bendersky

Reputation: 273366

>>> ls
[u'Cancer', u"Men's", u'Orthopedics', u'Pediatric', u"Senior's", u"Women's"]
>>> ls.sort()
>>> ls
[u'Cancer', u"Men's", u'Orthopedics', u'Pediatric', u"Senior's", u"Women's"]

Since the list was sorted in the first place, it didn't change. sort has no problem with ' - but note that it sorts before the a-z and A-Z characters:

>>> ls
[u'abc', u'abz', u"ab'"]
>>> ls.sort()
>>> ls
[u"ab'", u'abc', u'abz']
>>> 

Upvotes: 3

Related Questions