Python sort list by first number in a string

Convert to int after splitting on . to take the full numbers, not just the first digit:

lst = next(walk(self.rootDirectory))[1]
dirs = sorted(lst, key=lambda x: int(x.split('.')[0]))

To sort when the '.' are not certain to be in the strings:

dirs = sorted(lst, key=lambda x: float(x.split()[0]))

Works with or without the '.'.

Leave a Comment