Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a string in lexicographic order python

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?

like image 920
Bipul Jain Avatar asked Sep 10 '11 13:09

Bipul Jain


People also ask

What is sorting in lexicographic order?

A lexicographic order is an arrangement of characters, words, or numbers in alphabetical order, that is, the letters are sorted from A-Z. This is also known as dictionary order because it is similar to searching for a particular word in an actual dictionary.

How do you check if a string is lexicographically in Python?

You can use ( > , < , <= , <= , == , != ) to compare two strings. Python compares string lexicographically i.e using ASCII value of the characters. Suppose you have str1 as "Mary" and str2 as "Mac" .

How do you sort numbers in lexicographical order?

When applied to numbers, lexicographic order is increasing numerical order, i.e. increasing numerical order (numbers read left to right). For example, the permutations of {1,2,3} in lexicographic order are 123, 132, 213, 231, 312, and 321. When applied to subsets, two subsets are ordered by their smallest elements.


1 Answers

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).

like image 135
JBernardo Avatar answered Sep 23 '22 15:09

JBernardo