ACan
ACan

Reputation: 85

How to sort a list by integer between two values?

I have the following list:

['RC103_', 'RC109_', 'RC114_', 'RC115_', 'RC111_', 'RC100_', 'RC117_', 'RC104_', 'RC122_', 'RC120_', 'RC101_', 'RC121_', 'RC125_', 'RC116_', 'RC118_', 'RC119_', 'RC102_', 'RC129_', 'RC126_', 'RC12_4']

If I try to sort this list, I get this output:

   ['RC100_', 'RC101_', 'RC102_', 'RC103_', 'RC104_', 'RC109_', 'RC111_', 'RC114_', 'RC115_', 'RC116_', 'RC117_', 'RC118_', 'RC119_', 'RC120_', 'RC121_', 'RC122_', 'RC125_', 'RC126_', 'RC129_', 'RC12_4']

How can I sort this list so that RC12_4 is at the top? To be clear, I want this:

['RC12_4', 'RC100_', 'RC101_', 'RC102_', 'RC103_', 'RC104_', 'RC109_', 'RC111_', 'RC114_', 'RC115_', 'RC116_', 'RC117_', 'RC118_', 'RC119_', 'RC120_', 'RC121_', 'RC122_', 'RC125_', 'RC126_', 'RC129_']

What I want to do is sort by the value between 'RC' and the underscore. I know that to sort by, for instance, the first group created by '_' is to use:

sorted(listName, key=lambda x: x.split('_')[0])

Is there a way to modify this script so that it sorts by the first item after RC and before the underscore? Or is there an easier way? 

Also I have tried the natural keys approach and it didn't work for me.

Upvotes: 1

Views: 241

Answers (1)

Brian McCutchon
Brian McCutchon

Reputation: 8584

Convert it to int:

sorted(listName, key=lambda x: int(x.split('_')[0][2:]))

Upvotes: 4

Related Questions