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