Split the item on whitespace, take the second half, convert it into an integer, and sort using that.
>>> showslist = ("test 2", "test 4", "test 1", "test 9", "test 10", "test 11", "test 6", "test 3")
>>> sorted(showslist, key=lambda item: int(item.split()[1]))
['test 1', 'test 2', 'test 3', 'test 4', 'test 6', 'test 9', 'test 10', 'test 11']
partition
also works, but you're accessing the zeroth element of the return value ("test"), instead of the second (the number.)
>>> sorted(showslist, key=lambda item: int(item.partition(' ')[2]))
['test 1', 'test 2', 'test 3', 'test 4', 'test 6', 'test 9', 'test 10', 'test 11']
It looks like your final conditional is trying to ensure that the string has a numerical component at all, which is a good idea, although checking that the 0th character of item
is a digit won't do you much good here, since that's "t" for all of the items you've shown.
>>> showslist = ("test 2", "test 4", "oops no number here", "test 3")
>>> sorted(showslist, key=lambda item: int(item.partition(' ')[2]) if ' ' in item and item.partition(' ')[2].isdigit() else float('inf'))
['test 2', 'test 3', 'test 4', 'oops no number here']
If you want to sort first by the textual component, and then the numerical component, you can write a function that takes an item and returns a (text, number) tuple, which Python will sort the way you want.
def getValue(x):
a,_,b = x.partition(" ")
if not b.isdigit():
return (float("inf"), x)
return (a, int(b))
showslist = ("Atest 2", "Atest 4", "Atest 1", "Atest 9", "Atest 10", "Btest 11", "Btest 6", "Ctest 3")
print sorted(showslist, key=getValue)
#result: ['Atest 1', 'Atest 2', 'Atest 4', 'Atest 9', 'Atest 10', 'Btest 6', 'Btest 11', 'Ctest 3']
This can be done in one line, although you lose more in readability than you gain in file size:
print sorted(showslist, key= lambda x: (lambda a, _, b: (a, int(b)) if b.isdigit() else (float("inf"), x))(*x.partition(" ")))