Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list with alphanumeric items by letter first

I have such a list with alphanumeric items:

['A08', 'A09', 'A02', 'A03', 'A06', 'A07', 'A04', 'A05', 'A15', 'A14', 'A17', 'A16', 'A11', 
 'B01', 'B03', 'B02', 'B05', 'B04', 'B07', 'B06', 'B09', 'B08', 'B16', 'B17', 'B14', 'B15', 
 'C05', 'C06', 'C07', 'C19', 'C13', 'C12', 'C11', 'C10', 'C17', 'C16', 'C15', 'C14', 'C22', 
 'D02', 'D01', 'D09', 'D08', 'D14', 'D10', 'D11', 'D12', 'D15', 'D16', 'D17', 'D13', 
 'E08', 'E09', 'E06', 'E07', 'E04', 'E05', 'E02', 'E03', 'E01', 'E11', 'E10', 'E13', 'E12', 'E15', 'E14', 'E17', 'E16', 
 'F05', 'F04', 'F07', 'F06', 'F01', 'F03', 'F02', 'F09', 'F08', 'F12', 'F13', 'F10', 'F11', 'F16', 'F17', 'F14', 'F15', 
 'G08', 'G09', 'G04', 'G05', 'G06', 'G07']

I'm trying to sort it in such an order, using sorted method:

['A01', 'B01', 'C01',
 'A02', 'B02', 'C02',
 'A03', 'B03', 'C03']

but what I get is:

['A01', 'A02', 'A03',
 'B01', 'B02', 'B03',
 'C01', 'C02', 'C03']

I tried passing several keys to sorted, but I can't quite figure it out.

What key should I use? Or should I use another method?

like image 315
Anna Avatar asked Sep 10 '18 09:09

Anna


1 Answers

what you need is to prioritize the numeric part, so just create a key function yielding a tuple with first the numeric part, then the letter part, and let natural tuple ordering do the rest.

print(sorted(lst,key = lambda x : (x[1:],x[0])))

the numeric part doesn't need to be converted to integer as long as there are an even number of digits (zero-padded)

With such an input:

lst = ['A01', 'A02', 'A03',
 'B01', 'B02', 'B03',
 'C01', 'C02', 'C03']

you get:

['A01', 'B01', 'C01', 'A02', 'B02', 'C02', 'A03', 'B03', 'C03']

(if you want to protect your list against empty elements do lambda x : (x[1:],x[0]) if x else tuple()), although that defeats the idea of a sorted list with formatted elements)

like image 83
Jean-François Fabre Avatar answered Oct 05 '22 13:10

Jean-François Fabre