0

I have a list of strings that I am trying to organize numerically it looks like this :

List=['Core_0_0.txt', 'Core_0_1.txt','Core_0_2.txt',...'Core_1_0.txt','Core_2_3.txt',  ]

but when I sort it sorted(List)

It doesn't sort the list properly. It's very important that I keep the values as strings and they must be ordered by the number; I.E. 0_1, 0_2,0_3....31_1, they all have Core_X_X.txt How would I do this.

Dave
  • 23
  • 4

2 Answers2

1

If you can assume all your entries will look like *_N1_N2.txt, you can use the str.split method along with a sorting key function to sort your list properly. It might look something like this

sorted_list = sorted(List, key = lambda s: (int(s.split("_")[1]), int(s.split("_")[2].split(".")[0])))

Essentially, this internally creates tuples like (N1, N2) where your file is named *_N1_N2.txt and sorts based on the N1 value. If there's a tie, it will resort to the N2 value.

SyntaxVoid
  • 2,501
  • 2
  • 15
  • 23
  • 1
    You could shorten the `key` expression to: `key=lambda s: s.split(".")[0].split("_")[1:]` – PMende May 02 '19 at 20:03
  • 1
    I think that will run into trouble if the numbers are more than 1 digit long -- since they will be returned as `str` by `split` and sorting numbers as strings results in `"10"` < `"2"`. We'd have to do `key = lambda s: [int(i) for i in s.split(".")[0].split("_")[1:]]` – SyntaxVoid May 02 '19 at 20:10
0

Your question is a possible duplicate of another question. Which I am posting for you here again. you just need to change 'alist' to your 'List'.

import re

def atoi(text):
    return int(text) if text.isdigit() else text

def natural_keys(text):
    '''
    alist.sort(key=natural_keys) sorts in human order
    http://nedbatchelder.com/blog/200712/human_sorting.html
    (See Toothy's implementation in the comments)
    '''
    return [ atoi(c) for c in re.split(r'(\d+)', text) ]

alist=[
    "something1",
    "something12",
    "something17",
    "something2",
    "something25",
    "something29"]

alist.sort(key=natural_keys)
print(alist)

yields

['something1', 'something2', 'something12', 'something17', 'something25', 'something29']