user4758796
user4758796

Reputation:

Sort by a specific part of an element which is a string inside a list

I have a list which is as follows:

list = [ 'hello (abd)', 'goodbye (aab)', 'leave (aaa)' ]

is there a way to sort the list alphabetically by what is in the brackets? so for example the output would look like this:

sorted_list = ['leave (aaa)', 'goodbye (aab)', 'hello (abd)']

i have tried:

sorted(list)

but obviously that ust sorts it by the first letter. I am running python 3.4.

Upvotes: 1

Views: 33

Answers (2)

JuniorCompressor
JuniorCompressor

Reputation: 20025

You can use regular expression \(.+\), which will match inside the parentheses. Then re.search will be used as key function to sorting the list:

>>> import re
>>> l = ['hello (abd)', 'goodbye (aab)', 'leave (aaa)']
>>> sorted(l, key=lambda s: re.search(r"\(.+\)", s).group(0))
['leave (aaa)', 'goodbye (aab)', 'hello (abd)']

Upvotes: 1

Tim
Tim

Reputation: 43314

Use a lambda to sort

>>> l = ['hello (abd)', 'goodbye (aab)', 'leave (aaa)']
>>> sorted(l, key=lambda x: x[x.find('(')+1:x.find(')')])
['leave (aaa)', 'goodbye (aab)', 'hello (abd)']

It slices each string in the list from ( to ) and sorts on what's in that 'slice'.

Upvotes: 2

Related Questions