-1

Been googling for a while but can't seem to find answer that I can get to work.

I want this list -

sws = ['C6', 'A4', 'B8', 'A8', 'B11', 'C3', 'C5']

to be sorted to -

sws = ['A4', 'A8', 'B8', 'B11', 'C3', 'C5', 'C6']

I can get close but I can't seem to get B11 and B8 the right way round ie. B11 always comes before B8 in my list.

Thanks

martineau
  • 119,623
  • 25
  • 170
  • 301
jms
  • 31
  • 2

3 Answers3

1

You could also use natsort here, which helps with human-intuitive sorting:

>>> import natsort
>>> natsort.natsorted(sws)
['A4', 'A8', 'B8', 'B11', 'C3', 'C5', 'C6']
Tom
  • 8,310
  • 2
  • 16
  • 36
0

This can be done with a single liner -

sws.sort(key=lambda x: (x[0], int(x[1:])))

print(sws)
# ['A4', 'A8', 'B8', 'B11', 'C3', 'C5', 'C6']

Explanation:
A list of tuples is sorted by the first element, then the second, etc.
the .sort() method can sort according to a function, and in this specific case the function is a simple lambda function that returns a two-tuple consisting of the letter, and then the numerical value of the rest of the string (which is assumed to be a number).
Combining these two properties gives rise to the in-place sorting that you described.

ShlomiF
  • 2,686
  • 1
  • 14
  • 19
0

You can use a function to modify the sort key of each list item, without altering the original list contents:

def sort_key(text: str):
    letter = text[0]   # the first char
    digits = text[1:]  # everything after the first char
    return (letter, int(digits))

>>> sws = ['C6', 'A4', 'B8', 'A8', 'B11', 'C3', 'C5']
>>> sorted(sws, key=sort_key)
['A4', 'A8', 'B8', 'B11', 'C3', 'C5', 'C6']
damon
  • 14,485
  • 14
  • 56
  • 75