0

I'm currently building a program and am wondering how to sort a alphanumerical list like the one below, based on smallest to biggest number.

array1 = ["14f","9c","2d","7a"]

I would just like the numbers to sort like this ["2d","7a","9c","14f"]

Any help is appreciated.

blhsing
  • 91,368
  • 6
  • 71
  • 106
newtinn
  • 17
  • 3
  • You can turn it to a list of numbers by turning each string to it's hex value, then sorting a list of numbers is a well known problem. – Yonlif Feb 07 '19 at 19:17
  • 1
    Is this a hex value? i.e. if the list is `['1ff', '2a']`, which one goes first? – r.ook Feb 07 '19 at 19:22

1 Answers1

1

You could use sorted with a custom key function in order to sort the list:

import re
sorted(array1, key = lambda x: int(re.search(r'\d+', x)[0]))
# ['2d', '7a', '9c', '14f']

Where this custom key function is extracting the number within each string using re.search:

[int(re.search(r'\d+', i)[0]) for i in array1] 
# [14, 9, 2, 7]
yatu
  • 86,083
  • 12
  • 84
  • 139