Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

sorting

I have a list of strings that have 2 dashes separating text like:

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

I'd like to sort the list in alphabetical order in python by the last part of the string--the 2nd dash and on. Is there a way to do this in python? E.g. this is what I would want the list to look like after sorting.

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

(I'm using Python 2.6.)

like image 556
Jim Avatar asked Dec 22 '22 15:12

Jim


1 Answers

You can use the key attribute to 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 the split() call allows for more than 2 dashes. Every dash after the second one will be ignored and included in the third part.

like image 135
Sven Marnach Avatar answered Dec 24 '22 03:12

Sven Marnach