Sort list of strings by a part of the string
I have a list of strings which have the following format:
['variable1 (name1)', 'variable2 (name2)', 'variable3 (name3)', ...]
... and I want to sort the list based on the (nameX)
part, alphabetically. How would I go about doing this?
To change sorting key, use the key
parameter:
>>>s = ['variable1 (name3)', 'variable2 (name2)', 'variable3 (name1)']
>>> s.sort(key = lambda x: x.split()[1])
>>> s
['variable3 (name1)', 'variable2 (name2)', 'variable1 (name3)']
>>>
Works the same way with sorted
:
>>>s = ['variable1 (name3)', 'variable2 (name2)', 'variable3 (name1)']
>>> sorted(s)
['variable1 (name3)', 'variable2 (name2)', 'variable3 (name1)']
>>> sorted(s, key = lambda x: x.split()[1])
['variable3 (name1)', 'variable2 (name2)', 'variable1 (name3)']
>>>
Note that, as described in the question, this will be an alphabetical sort, thus for 2-digit components it will not interpret them as numbers, e.g. "11" will come before "2".
You can use regex for this:
>>> import re
>>> r = re.compile(r'\((name\d+)\)')
>>> lis = ['variable1 (name1)', 'variable3 (name3)', 'variable2 (name100)']
>>> sorted(lis, key=lambda x:r.search(x).group(1))
['variable1 (name1)', 'variable2 (name100)', 'variable3 (name3)']
Note that above code will return something like name100
before name3
, if that's not what you want then you need to do something like this:
>>> r = re.compile(r'\(name(\d+)\)')
def key_func(m):
return int(r.search(m).group(1))
>>> sorted(lis, key=key_func)
['variable1 (name1)', 'variable3 (name3)', 'variable2 (name100)']
The solution is:
sorted(b, key = lambda x: x.split()[1])
Why? We want to sort the list (called b). As a key we will use (name X). Here we assume that it will be always preceded by space, therefore we split the item in the list to two and sort according to the second.
Just use key
parameter of sort
method:
test.sort(key = lambda x: x.split("(")[1])
Edit: test
is the array.