2

I have a list of strings for which I would like to perform a descending numerical and then ascending alphabetical sort.

For instance, the following list needs to be sorted:

['120d', '120a', '1080p', '1080a', '696p', '696z']

What is want as the output:

['1080a', '1080p', '696p', '696z', '120a', '120d']

What I get when I use sorted function of python:

['1080a', '1080p', '120a', '120d', '696p', '696z']

What I get when I use natsorted (from this post) function of python:

['120a', '120d', '696p', '696z', '1080a', '1080p']

I would be glad if anyone can assist me or guide me on the right track. Thank you

Simplified code:

from natsort import natsorted

f = ['120d', '120a', '1080p', '1080a', '696p', '696z']
print ("ACTUAL:")
print (f)
print ()

f_sorted = sorted(f)
print ("SORTED:")
print (f_sorted)
print ()

f_natsorted = natsorted(f)
print ("NATSORTED:")
print (f_sorted)
print ()

desired = ['1080a', '1080p', '696p', '696z', '120a', '120d']
print ("WANTED:")
print (desired)
t.abraham
  • 108
  • 1
  • 9

2 Answers2

2

In case the non-numeric part isn't always the same size (or even present):

import re 
def na_split(s):
    # Split the string into leading numeric & rest
    n,s = re.fullmatch('^([0-9]+)(.*)$',s).groups()
    return (-int(n),s)
data = ['120d', '120a', '1080p', '1080a', '696p', '696z', '480', '480a', '480p']
print(sorted(data,key=lambda x:na_split(x)))

>> ['1080a', '1080p', '696p', '696z', '480', '480a', '480p', '120a', '120d']
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

Try this:

print(sorted(yourlist, key=lambda x: (-int(x[:-1]), x[-1])))

Output:

['1080a', '1080p', '696p', '696z', '120a', '120d']
U13-Forward
  • 69,221
  • 14
  • 89
  • 114