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?
CodePudding user response:
To sort this list according to the digits inside the strings, you can use the sorted() function with a custom key function. The key function can extract the number from each string and return it, so that sorted() sorts the list based on these numbers. Here's an example implementation in Python:
lst = ['American (New):182', 'American (Traditional):181', 'Asian Fusion:177', 'Brazilian:8', 'Canadian (New):345', 'Caribbean:13']
def extract_number(string):
return int(string.split(':')[1])
sorted_lst = sorted(lst, key=extract_number)
print(sorted_lst)
# ['Brazilian:8', 'Caribbean:13', 'Asian Fusion:177', 'American (Traditional):181', 'American (New):182', 'Canadian (New):345']
CodePudding user response:
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]))
CodePudding user response:
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)
CodePudding user response:
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']