'Sorting elements in order while leaving some intact

Hi everyone I'm quite new to Python and I'm trying to figure out how to sort the elements in this list in a particular order

What I have:

lst = ['1. [a] -1  +2, 2. [b] ++3  +4  -1, 3. [c] +5  -E1, 4. -E1', '1. [d] +6  -7  ++8, 2. [e] -E1  +9']

I want to keep the order of the first elements and only change around the order of the numbers, in the order of

(++ + - -- )

So what I'm after is:

lst = ['1. [a] +2  -1, 2. [b] ++3  +4  -1, 3. [c] +5  -E1, 4. -E1', '1. [d] ++8 +6  -7, 2. [e] +9 -E1']

I've tried using the sort and sorted method, to no avail

I have no idea how to go about this, some help would be appreciated

Please go easy on me this is my first post and I'm new to Python



Solution 1:[1]

The sort and sorted functions take an additional parameter called key that lets you specify the sort order.

For your example - the sorting order is defined by a precedence list that you have defined - i.e.

precedence = ['++', '+', '-', '--']

You need to define a function that uses this precedence list to return a "sort rank" - for example

def sorting_func(s):
    if s[:2] in precedence:
        return precedence.index(s[:2]) + 1
    elif s[:1] in precedence:
        return precedence.index(s[:1]) + 1
    return 0

And apply this function to your elements -

sorted_lst = []
for element in lst:
    first_split = element.split(',')
    second_split = [_.split() for _ in first_split]
    sorted_second_split = [sorted(_, key = sorting_func) for _ in second_split]
    first_rejoin = [' '.join(_) for _ in sorted_second_split]
    second_rejoin = ', '.join(first_rejoin)
    sorted_lst.append(second_rejoin)

Output

['1. [a] +2 -1, 2. [b] ++3 +4 -1, 3. [c] +5 -E1, 4. -E1',
 '1. [d] ++8 +6 -7, 2. [e] +9 -E1']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mortz