Sort a string in lexicographic order python

52,656

Solution 1

Do not use lambda functions when there's builtin ones for the job. Also never use the cmp argument of sorted because it's deprecated:

sorted(s, key=str.lower)

or

sorted(s, key=str.upper)

But that may not keep 'A' and 'a' in order, so:

sorted(sorted(s), key=str.upper)

that will and, by the nature of sorted the operation will be very fast for almost sorted lists (the second sorted).

Solution 2

You could use a 2-tuple for the key:

text='aAaBbcCdE'
sorted(text, key=lambda x: (str.lower(x), x))
# ['A', 'a', 'a', 'B', 'b', 'C', 'c', 'd', 'E']

The first element in the tuple, str.lower(x) is the primary key (making a come before B), while x itself breaks ties (making A come before a).

Solution 3

cmp was the old way of doing this, now deprecated, but for posterity:

s='aAaBbcCdE'
sorted(s, lambda x,y: cmp(x.lower(), y.lower()) or cmp(x,y))

Solution 4

data = input() data=list(data) data.sort()

Now the variable "data" will have lexicographically sorte`d input provided.

Share:
52,656

Related videos on Youtube

Bipul Jain
Author by

Bipul Jain

Python , Django, Web, Search and Data. I design and develop for web applications and backend development. Interested in short-term and mid-term projects.

Updated on July 27, 2021

Comments

  • Bipul Jain
    Bipul Jain almost 3 years

    I want to sort a string to a list in lexicographic order as

    str='aAaBbcCdE'
    

    to

    ['A','a','a','B','b','C','c','d','E']
    

    but sorted() gives me this output:

    ['A','B','C','E','a','a','b','c','d']
    

    How can I sort lexicographically?

  • JBernardo
    JBernardo over 12 years
    that's deprecated use of sorted.
  • Russia Must Remove Putin
    Russia Must Remove Putin about 9 years
    @KarolyHorvath to be completely obvious, fix your answer and he won't have to.
  • Karoly Horvath
    Karoly Horvath about 9 years
    @AaronHall: which will make the comments misleading. no, thanks.
  • Antti Haapala -- Слава Україні
    Antti Haapala -- Слава Україні about 9 years
    Actually, let's keep this answer here :D
  • Abhijeet
    Abhijeet over 5 years
    sorted(sorted(s), key=str.upper) stands-out.
  • Scott Gartner
    Scott Gartner almost 3 years
    This solved it for me, but I don't understand why returning x doesn't result in correct sorting, but returning (lower(x), x) does. Can anyone explain?
  • Raffi
    Raffi over 2 years
    @ScottGartner returning a 2-uple (lower(x), x) basically uses the already implemented lexicographical ordering of the tuples: all elements that are equal on the index 0 of the tuple will be sorted by the element of the index 1 of the tuple, all elements that are different on index 0 will be sorted as usual.
  • Raffi
    Raffi over 2 years
    This is the best answer by far!