4

I have a list that its elements are composed of a letters and numbers as shown below :

['H1', 'H100', 'H10', 'H3', 'H2', 'H6', 'H11', 'H50', 'H5', 'H99', 'H8'] 

I wanted to sort it, so I used the function sort, but I got as output :

>>> a = ['H1', 'H100', 'H10', 'H3', 'H2', 'H6', 'H11', 'H50', 'H5', 'H99', 'H8']
>>> print sorted(a)
['H1', 'H10', 'H100', 'H11', 'H2', 'H3', 'H5', 'H50', 'H6', 'H8', 'H99']

However, I want the output to be :

['H1', 'H2', 'H3', 'H5', 'H6', 'H8', 'H10', 'H11', 'H50', 'H99', 'H100']

Does anyone has an idea how to do this please? Thank you

singrium
  • 2,746
  • 5
  • 32
  • 45

1 Answers1

8
l = ['H1', 'H100', 'H10', 'H3', 'H2', 'H6', 'H11', 'H50', 'H5', 'H99', 'H8']
print sorted(l, key=lambda x: int("".join([i for i in x if i.isdigit()])))

Output:

['H1', 'H2', 'H3', 'H5', 'H6', 'H8', 'H10', 'H11', 'H50', 'H99', 'H100']
cs95
  • 379,657
  • 97
  • 704
  • 746
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • Thank you, a very simple and clear solution. – singrium Mar 12 '18 at 10:32
  • You are welcome :). – Rakesh Mar 12 '18 at 10:35
  • Hello @Rakesh, Could you please explain this part . `int("".join([i for i in x if i.isdigit()]))` . Why `isdigit` is not giving false because i think it is working like this `isdigit('H1')` , `isdigit('H100')`.... – PIG Mar 12 '18 at 11:07
  • 1
    @PIG This snippet gets the digit part of the string. For example 'H100' becomes 100. `for i in x if i.isdigit()` goes letter by letter and checks if the letter is digit or not. If it's digit it will add to the list. When we do `"".join` we then combine all elements of the list, that is the digits of a string together with empty separator, i.e. "". – Sergey Ivanov Mar 12 '18 at 11:18
  • @SergeyIvanov Thanks – Rakesh Mar 12 '18 at 11:21
  • @SergeyIvanov Which part of the code is removing character part from digit. For eg , expected should be `'H100'` , but which part of code giving input as `'100'` . . I am not understanding this part only. – PIG Mar 12 '18 at 11:31
  • @Rakesh My question is which part of coding is segregating `'H'` and `'101'` . Please explain. – PIG Mar 12 '18 at 11:57
  • @PIG. I am iterating over the string 'H100' and testing each element if it is a digit or not using the isdigit method if it is a digit I am concatenating them – Rakesh Mar 12 '18 at 12:38