Complicated sorting in Python
Question: I need to sort a list of strings.

However, I do not want to sort it using the first character, so I cannot use
`.sort()`

I have a list:

    
    
    records = ["Bibble - 1300 / 2000",
    "Jim Foo - 900 / 2000",
    "Bibble - 1600 / 2000",
    "Bibble - 1000 / 2000"]
    

I want to sort by their score out of 2000. I want an output that looks
something like this:

    
    
    >>> Jim Foo - 900 / 2000
    Bibble - 1000 / 2000
    Bibble - 1300 / 2000
    Bibble - 1600 / 2000
    

In the example above, I sorted it by smallest to largest. I also want to know
how I would sort this list biggest score to smallest score.

I've tried `.sort()`, but It's nothing like what I want. `.sort()` sorts it
with the first character which I do not want:

    
    
    >>> records.sort()
    >>> records
    ['Bibble - 1000 / 2000', 'Bibble - 1300 / 2000', 'Bibble - 1600 / 2000', 'Jim Foo - 900 / 2000']
    >>> 
    

Is there anyway of doing this, possibly in regular expression?

Is it also possible, so if i were to add more scores into the list I would
still be able to sort it this way?


Answer: You can use `sorted` function with a proper `key` and use `re.split` :

    
    
    >>> import re
    >>> sorted(records,key=lambda x:int(re.split(r'[-/]',x)[1].strip()))
    ['John Smith - 900 / 2000',
     'Bob Foo - 1000 / 2000', 
     'Bob Foo - 1300 / 2000', 
     'Bob Foo - 1600 / 2000']
    

The `sorted` function sort your list based on its key function, and your key
split your elements with `re.split` with function as following :

    
    
    re.split(r'[-/]',x)
    

the pattern `[-/]` split your string based on `-` or `/`.

for example :

    
    
    >>> re.split(r'[-/]',"Bob Foo - 1600 / 2000")
    ['Bob Foo ', ' 1600 ', ' 2000']
    

and then you need to `strip()` to remove the leading and trailing spaces. then
convert to int and sort your list based on that value!

