-3

I have the following list

keys = [u'3_sd', u'14_sd', u'16_sd', u'13_sd', u'4_sd', u'18_sd', u'22_sd', u'1_sd', u'6_sd', u'7_sd', u'15_sd', u'21_sd', u'19_sd', u'10_sd', u'2_sd', u'17_sd', u'8_sd', u'11_sd', u'9_sd', u'12_sd', u'5_sd', u'20_sd']

when i sort it like keys.sort() the result was

[u'10_sd',u'11_sd',u'12_sd',u'13_sd',u'14_sd',u'15_sd',u'16_sd',u'17_sd',u'18_sd',u'19_sd',u'1_sd',u'20_sd',u'21_sd',u'22_sd',u'2_sd',u'3_sd',u'4_sd',u'5_sd',u'6_sd',u'7_sd',u'8_sd',u'9_sd']

But i need them to sort in numerical ascending order like

[u'1_sd',u'2_sd',u'3_sd',u'4_sd',u'5_sd',u'6_sd'.......]

I have seen some other ways on google sorted(keys, key=int), which was not working in my case since the elements in the list are strings, so is there a way to sort them in ascending order without manipulating the data in list ?

Shiva Krishna Bavandla
  • 25,548
  • 75
  • 193
  • 313
  • You will have to convert the appropriate part to integer, e.g. `int(item.split('_', 1)[0])`, and use that as the key. – jonrsharpe Jul 21 '16 at 06:14
  • You are dealing with strings, and python will sort them literally. If you want to sort based on first digit you need to split the string and convert the digit to integer. `sorted(keys, key=lambda x: int(x.split('_')[0]))` – Mazdak Jul 21 '16 at 06:15
  • you said it, they are strings so they will be sorted like that unless you extract the number –  Jul 21 '16 at 06:15

1 Answers1

2

Just use a sufficiently complex key.

key=lambda x: int(x.split('_')[0])
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358