Home python Convert string to the list with sorting in lexicographic order

Convert string to the list with sorting in lexicographic order




How to convert a string consisting of words separated by spaces, to the list, and sort the resulting list in lexicographic order?

Dana row from words separated by spaces:

s = 'abc a bcd bc ABC BC BCD BCD ABC'

We transform it into the list, with the “Space” separator:

a = s.split ('')

We get:

['abc', 'a', 'bcd', 'bc', 'abc', 'bc' , 'BCD', 'BCD', 'ABC']

If you do now:

a = a.sort ()
Print (A)

We do not get anything, if so:

b = a.sort ()
Print (A)

We get a sorted list

['abc', 'abc', 'bc', 'bcd', 'a', 'abc' , 'BC', 'BCD', 'BCD']

Why so? Is it possible to somehow combine sort () and split () in one line?

Answer 1, Authority 100%

Because a.sort () simply assorts a (the list “just” becomes sorted), and does not return anything, but the functions do not return anything in Python in fact Return None . If you a = a.sort () , you first sort a , and then write down on top of it none .

need to do or so:

a = a.split ('')
a.sort ()
Print (A)

or so if you need one string:

print (sorted (a.split (''))

The difference is that the list.sort () method changes the source list, and does not return anything, and the sorted () function does not change the source list, but returns it Sorted copy.

Answer 2, Authority 120%

it’s just:

a = sorted (s.split (''))

in reverse order:

a = sorted (s.split (''), reverse = true)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions