SoljaragCNC
SoljaragCNC

Reputation: 45

Python Sort List, Skipping a Character

I have a list of:

list = ["S9_1-", "S10_E1-17", "S25_1-21", "S3_1-", "S5_1-"] 

if I do print sorted(list) I get:

['S10_E1-17', 'S25_1-21', 'S3_1-', 'S5_1-', 'S9_1-']

Is there a way I can ignore the letters, so it sorts it as:

['S3_1-', 'S5_1-', 'S9_1-', 'S10_E1-17', 'S25_1-21']

Upvotes: 0

Views: 326

Answers (2)

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23203

seq = ["S9_1-", "S10_E1-17", "S25_1-21", "S3_1-", "S5_1-"] 
sorted_seq = sorted(seq, key=lambda item: int(item.split("_")[0][1:]))
assert sorted_seq == ['S3_1-', 'S5_1-', 'S9_1-', 'S10_E1-17', 'S25_1-21']

Upvotes: 5

inspectorG4dget
inspectorG4dget

Reputation: 113915

What you are looking for is the optional key argument in sort. You can use it to tell python to sort based on a function. In this case, that function can be expressed as follows:

def mykey(s):
    parts = s.split("_",1)
    importantPart = splits[0]
    number = int(importantPart[1:])  # remove the "S"
    return number

Of course, this can be expressed as a simple lambda:

lambda s: int(s.split("_",1)[0][1:])

And thus, you get the following:

In [21]: L = ['S10_E1-17', 'S25_1-21', 'S3_1-', 'S5_1-', 'S9_1-']

In [22]: sorted(L, key=lambda s: int(s.split("_",1)[0][1:]))
Out[22]: ['S3_1-', 'S5_1-', 'S9_1-', 'S10_E1-17', 'S25_1-21']

Upvotes: 6

Related Questions