开发者

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

开发者 https://www.devze.com 2023-02-23 09:34 出处:网络
I have a list of strings that have 2 dashes separating text like: Wednesday-Morning-Go bowling Sunday-Really late at night-Sleep

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


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.


Simply use either sort or sorted providing as the optional key parameter a function that will extract the key you want to sort on. In this case, it is done by splitting the string on the - character and pick the last component.

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


The sort function can take a key parameter that specifies a function to call on each element before comparing 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 )


Use the key parameter of sorted:

>>> 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']
0

精彩评论

暂无评论...
验证码 换一张
取 消