1

I'm new to python and I'm trying to sort a list alpha numeric.

I've seen other answers here and tried to figure it out by myself, but can fix this one!

lets say I have this list:

showslist = ("Atest 2", "Atest 4", "Atest 1", "Atest 9", "Atest 10", "Btest 11", "Btest 6", "Ctest 3")

sortfiles = sorted(showslist, key=lambda item: (int(item.partition(' ')[0])
                                   if item[0].isdigit() else float('inf'), item))
for i in sortfiles:
    print i

this returns:

Atest 1 Atest 10 Atest 2 Atest 4 Atest 9 Btest 11 Btest 6 Ctest 3

and should return:

Atest 1 Atest 2 Atest 4 Atest 9 Atest 10 Btest 6 Btest 11 Ctest 3

can anyone help me out with this please Thanks so much in advance.

kiko va
  • 55
  • 2
  • 7

1 Answers1

1

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(" ")))
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • that worked for my question but My fault I post the list wrong. I just edit the list in the question. I need it to work alphabetically and numerically – kiko va Nov 06 '13 at 20:26