-1

Hello I have a string list:

['American (New):182', 'American (Traditional):181', 'Asian Fusion:177', 'Brazilian:8', 'Canadian (New):345', 'Caribbean:13']

I need to sort it according to the digits present inside the string. How can I do this?

Python analog of PHP's natsort function (sort a list using a "natural order" algorithm)

How to correctly sort a string with a number inside?

Looked at these and tried applying it to my program but didn't work. Maybe its the ':' thats making them not work properly?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Gng Sht
  • 19

3 Answers3

0

use key option of sort parse the number and use as key for sorting

lst=['American (New):182', 'American (Traditional):181', 'Asian Fusion:177', 'Brazilian:8', 'Canadian (New):345', 'Caribbean:13']
lst.sort(key=lambda x:int(x.split(":")[-1]))
print(lst)
['Brazilian:8', 'Caribbean:13', 'Asian Fusion:177', 'American (Traditional):181', 'American (New):182', 'Canadian (New):345']
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
geekay
  • 340
  • 1
  • 5
0

I would personally try and use a dictionary for this, but this should do the trick:

listname.sort(key=lambda x: int(x.split(':')[-1]))
B Remmelzwaal
  • 1,581
  • 2
  • 4
  • 11
  • 1
    I suggest either using `x.rsplit(':')[1]`, or `x.split(':')[-1]`, but not `x.split(':')[1]`, in order to make it more robust to a string that contains extra `':'` in the first part. For instance if `'Asian: Fusion:177'` is a string in the list, you want to isolate the right-most split element, not the element at position 1. – Stef Feb 03 '23 at 15:44
  • Absolutely true, I will include that. Thanks for the suggestion. – B Remmelzwaal Feb 03 '23 at 15:46
0

You can define a function that extracts the number from each string, then use it as a sorting key:

import re
def string_to_number(my_string):
    return int(re.findall(':(\d+)', my_string)[0])

a=['American (New):182', 'American (Traditional):181', 'Asian Fusion:177', 'Brazilian:8', 'Canadian (New):345', 'Caribbean:13']

sorted_a = sorted(a, key = string_to_number)
Swifty
  • 2,630
  • 2
  • 3
  • 21
  • It would be more robust to search for digits preceded by a colon – Pranav Hosangadi Feb 03 '23 at 15:53
  • Indeed; I based by implementation on there being only one number in the string (but then I could have simply split around the ':' ;) ); I'll update my answer, thanks. – Swifty Feb 03 '23 at 15:57