João Paulo
João Paulo

Reputation: 6690

Sort criteria - sorted()

I'd like to sort a list following two criteria in this order:

  1. Numerical order; then
  2. Alphabetical order.

I'm currently using:

from re import search
my_list = ['nelsonfreire87956423', 'martha34685128', 'gleen34685128', 'polini13452678']

first_sort = sorted(my_list, key=lambda x: [x])

sorted_list = sorted(
    first_sort, 
    key=lambda x: search(r'\d{8}', x).group() if search(r'\d{8}', x) else []
)
print(sorted_list)

Which gives the desired result:

['polini13452678', 'gleen34685128', 'martha34685128', 'nelsonfreire87956423']

I'd like to know how I can sort this list with just one sorted call. I mean, how can I pass multiple criteria to sorted?

Upvotes: 0

Views: 71

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122106

Your key function can return a tuple, where the elements at each position in the tuple are used to break ties from the elements at the previous position. For example:

def my_key(s):
    name, num = search(r'(\D+)(\d+)', s).groups()
    return int(num), name

which results in:

>>> my_key('nelsonfreire87956423')
(87956423, 'nelsonfreire')  # i.e. sort on number first, then name

and therefore:

>>> sorted(my_list, key=my_key)
['polini13452678', 'gleen34685128', 'martha34685128', 'nelsonfreire87956423']

Upvotes: 1

Related Questions