In python, how would I sort the list of strings where the string comparison location is changing?

I have a list of lines that have two dashes separating text like:

Wednesday-Morning-Go bowling Sunday-Really late at night-Sleep July-Noon-BBQ 

I would like to sort the list in alphabetical order in python by the last part of the line - the 2nd dash and beyond. Is there any way to do this in python? For instance. this is what I would like the list to look after sorting.

 July-Noon-BBQ Wednesday-Morning-Go bowling Sunday-Really late at night-Sleep 

(I am using Python 2.6.)

+4
source share
4 answers

You can use the key attribute for list.sort() :

 a = ["Wednesday-Morning-Go bowling", "Sunday-Really late at night-Sleep", "July-Noon-BBQ"] a.sort(key=lambda x: x.split("-", 2)[-1]) print a 

prints

 ['July-Noon-BBQ', 'Wednesday-Morning-Go bowling', 'Sunday-Really late at night-Sleep'] 

Note that calling split() allows more than two dashes. Each dash after the second will be ignored and included in the third part.

+8
source

Just use sort or sorted , providing as an optional key parameter a function that will retrieve the key you want to sort. In this case, this is done by dividing the string into a character - and selecting the last component.

sorted_list = sorted(mylist, key=lambda line: line.rsplit("-", 1)[-1])

+1
source

The sort function can take a key parameter, which indicates the function to call each element before matching it.

 def last_part( s ): return s.split('-')[-1] my_strings = ["Wednesday-Morning-Go bowling", "Sunday-Really late at night-Sleep", "July-Noon-BBQ"] my_strings.sort( key=last_part ) 
+1
source

Use the key sorted parameter:

 >>> L=['Wednesday-Morning-Go bowling','Sunday-Really late at night-Sleep','July-Noon-BBQ'] >>> sorted(L,key=lambda x: x.split('-')[2]) ['July-Noon-BBQ', 'Wednesday-Morning-Go bowling', 'Sunday-Really late at night-Sleep'] 
+1
source

Source: https://habr.com/ru/post/1347589/


All Articles