0

I have a list that looks a little like this: ['Number 10', 'Number 11', 'Number 1', 'Number 2'] How would I sort it so it is like: ['Number 1', 'Number 2', 'Number 10', 'Number 11'] Thanks for the help

4 Answers4

1

Natural Sorting

We can use natural sorting when trying to sort a list of strings with both characters and integers

import re

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

# natural sorting algorithm
def natural_keys(text):
 
    return [ atoi(c) for c in re.split(r'(\d+)', text) ]

a = ['Number 10', 'Number 11', 'Number 1', 'Number 2']
print(a)
a.sort(key=natural_keys)
print(a)

Gives the output:

['Number 10', 'Number 11', 'Number 1', 'Number 2']
['Number 1', 'Number 2', 'Number 10', 'Number 11']

There is also a third party library for this on PyPI called natsort by SethMMorton that has prebuilt function to do this.

0

Not sure if its the most efficient way but you could do something like this

values=["Number 1","Number 2", "Number 15", "Number 12","Number 10"]

["Number "+str(x) for x in sorted([int(y.split("Number ")[1]) for y in values])]
-1

Custom Key

To sort this, we need to treat the numbers without the 'Number ' prefix in front. We can do this by using a custom key, which just gets the number afterward by removing the front and converting to an integer. This retains all the information of the original list.

numberList.sort(key = lambda x: int(x[7:]))
Larry the Llama
  • 958
  • 3
  • 13
-2

lets say your initial list is named list_pre

list_post = []
for item in list_pre:
    list_post.append(int(item.split(' ')[1]))
list_post.sort()
for i in range(len(list_post)):
    list_post[i] = 'Number '+str(list_post[i])

there are ways with less lines of code, but given the question, you seem fairly new, so I tried to use basic functionality and easy to find built in methods.

AlbinoRhino
  • 467
  • 6
  • 23