0

How to do human sorting on below list, I want to sort based on last numbers e.g 45-50, 35-40 etc

list_list= ['N1-1TWS-AD03-____-001N-__45-50',
     'N1-1TWS-AD01-____-001N-__50-54',
     'N1-1TWS-AD01-____-001N-__54-58',
     'N1-1TWS-AD01-____-001N-__58-61',
     'N1-1TWS-AD01-____-001N-__61-65',
     'N1-2TWS-AD01-____-001S-__25-28',
     'N1-2TWS-AD01-____-001S-__25-28',
     'N1-3TWS-AD01-____-001S-__28-31',
     'N1-4TWS-AD01-____-001S-__28-31',
     'N1-3TWS-AD01-____-001S-__31-35',
     'N1-3TWS-AD01-____-001S-__31-35',
     'N1-3TWS-AD01-____-001S-__35-40',
     'N1-3TWS-AD01-____-001S-__35-40',
     'N1-3TWS-AD01-____-001S-__40-43',
     'N1-3TWS-AD01-____-001S-__40-43',
     'N1-3TWS-AD01-____-001S-__43-47']

I tried sort and sorted but it wasn't giving the result I wanted. I want to sort like

['N1-2TWS-AD01-____-001S-__25-28',
'N1-2TWS-AD01-____-001S-__25-28',
'N1-3TWS-AD01-____-001S-__28-31',
'N1-4TWS-AD01-____-001S-__28-31',
 ...and so on...
'N1-1TWS-AD01-____-001N-__61-65']
Royal
  • 218
  • 2
  • 17
  • 1
    Does this answer your question? [Is there a built in function for string natural sort?](https://stackoverflow.com/questions/4836710/is-there-a-built-in-function-for-string-natural-sort) – Ch3steR Nov 25 '20 at 18:57
  • @Ch3steR not quite, his problem is simple without multiple numbers in a single string – Royal Nov 25 '20 at 18:58
  • What do you mean by human sorting? Which strings do you want to come first and which next? – fdermishin Nov 25 '20 at 19:06
  • @user13044086 go google natural sorting aka human sorting – Royal Nov 25 '20 at 19:11
  • Judging from the way you've provided your ideal sorted result is it only the last two double digits you want to sort by? – Swazy Nov 25 '20 at 19:16
  • I've put a solution in the answers assuming that's what you mean. Let me know if you mean otherwise! – Swazy Nov 25 '20 at 19:25
  • @Swazy Is there a way to do it for df column ? I want columns to move as the key column – Royal Nov 25 '20 at 21:18
  • Hey @EegiiEnkhtaivan. I'm afraid I'm not quite sure what you mean. Do you mean there is another part of the string you would like to sort by as well? – Swazy Nov 25 '20 at 22:11
  • @Swazy Hi, Swazy. I mean is it possible to perform below in DF column ? – Royal Nov 25 '20 at 22:13
  • Oh you mean sort items in a pandas DataFrame column? – Swazy Nov 25 '20 at 22:23

1 Answers1

1

This should do the trick:

z = sorted(list_list, key=lambda s: (s[-5:-3], s[-2:]))
Swazy
  • 378
  • 3
  • 10
  • 1
    Probably `z = sorted(list_list, key=lambda s: s[:-5])` will be enough for the provided data – fdermishin Nov 25 '20 at 19:27
  • Yeah agreed. Thought it might be nice to be explicit about how you could extract specific integers from the string to sort by. Maybe more complicated than necessary though :) – Swazy Nov 25 '20 at 19:30