How to set up sorting of an alphanumeric list?

I have the following list

l = ['SRATT', 'SRATW', 'CRAT', 'CRA0', 'SRBTT', 'SRBTW', 'SRAT0', 'SRBT0']

which I would like to sort alphabetically, adding the rule that a line containing a number at the end (actually always 0) should appear after the last completely alphabetic line (the last letter is no more than W).

How can i do this? (using, if possible, a simple method, for example sorted)


In this list of examples, the desired result will be

['CRAT', 'CRA0', 'SRATT', 'SRATW' , 'SRAT0', 'SRBTT', 'SRBTW', 'SRBT0']

eg. following does not work

sorted(l, key=lambda x: x[-1].isdigit())

as it puts lines containing a finite number at the end e.g.

['SRATT', 'SRATW', 'CRAT', 'SRBTT', 'SRBTW', 'CRA0', 'SRAT0', 'SRBT0']
+6
source share
3 answers

The working solution is below !

First try:

>>> l = ['SRATT', 'SRATW', 'CRAT', 'CRA0', 'SRBTT', 'SRBTW', 'SRAT0', 'SRBT0']
>>> sorted(l, key=lambda x: (x[:-1], x[-1].isdigit()))
['CRAT', 'CRA0', 'SRATT', 'SRATW', 'SRAT0', 'SRBTT', 'SRBTW', 'SRBT0']

UPDATE

@StefanPochmann , .

,

>>> l = ['SRATT', 'SRATW', 'CRAT', 'CRA0', 'SRBTT', 'SRBTW', 'SRAT0', 'SRBT0', 'B', 'A']
>>> sorted(l, key=lambda x: (x[:-1], x[-1].isdigit(), x))
                                                      ^
                                             additional element
['A', 'B', 'CRAT', 'CRA0', 'SRATT', 'SRATW', 'SRAT0', 'SRBTT', 'SRBTW', 'SRBT0']

(, )

@Demosthene , , true

, ( ) , , . '{':

sorted(l, key=lambda x: ''.join((x[:-1], '{')) if x[-1].isdigit() else x)

sorted(l, key=lambda x: x[:-1] + '{' if x[-1].isdigit() else x)

@StefanPochmann. , .

+6

( ) : .

sorted(l, key=lambda x: (x[:-1] ,x[-1].isdigit()))

, :

sorted(l, key=lambda x: (x[:-1] if len(x)>1 and not x[-1].isdigit() else x,x[-1].isdigit() if x else False))

( , , 1 0 ['AB', 'AA'])

+4

: 0 Z:

>>> sorted(l, key=lambda x: x.replace('0', 'Z'))
['CRAT', 'CRA0', 'SRATT', 'SRATW', 'SRAT0', 'SRBTT', 'SRBTW', 'SRBT0']

(I assume there are no zeros in the string before, let me know if this is not the case.)

+2
source

Source: https://habr.com/ru/post/1014491/


All Articles