Sorting list with strings and numbers

Hi, how could I sort out the list from 1 onwards?
Any ideas are welcome!

image

@Clementine You need something called natural sort.

Try this:

import re

def natural_sort(l): 
    convert = lambda text: int(text) if text.isdigit() else text.lower() 
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] 
    return sorted(l, key = alphanum_key)
    
OUT = natural_sort(IN[0])

Alternatively, you can use the Natural Sort node from Orchid package

3 Likes

Thanks a lot!

1 Like

Please, make it work with lists in list

@gRanid19 Here you go:

import re
toNestList = lambda x: x if any(isinstance(i, list) for i in x) else [x]

def natural_sort(l): 
    convert = lambda text: int(text) if text.isdigit() else text.lower() 
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] 
    return sorted(l, key = alphanum_key)
    
OUT = [natural_sort(x) for x in toNestList(IN[0])]
1 Like