Home > Software engineering >  how to sort the elements in a list in numerical order and not alphabetical
how to sort the elements in a list in numerical order and not alphabetical

Time:12-28

i have a list containing sentences with numbers in it, i want to sort then numerically and not alphabetically. but when i use the sort function, it sorts the elements alphabetically and not numerically, how do i fix this?

num = ['ryan has 8 apples','charles has 16 bananas','mylah has 3 watermelons']
num.sort()
print(num)

output:
['charles.....','mylah.....','ryan......']

as you can see, it is sorted alphabetically but that is not my expected output

the dots represent the rest of the sentence

expected result:

['mylah has 3 watermelons','ryan has 8 apples','charles has 16 bananas']

here's the expected output where the elements are sorted numerically and not alphabetically

CodePudding user response:

The solutions so far focus on a solution specific to the structure of your strings but would fail for slightly different string structures. If we extract only the digit parts of the string and then convert to an int, we'll get a value that we can pass to the sort function's key parameter:

num.sort(
    key=lambda s: int(''.join(c for c in s if c.isdigit()))
)

The key parameter lets you specify some alternative aspect of your datum to sort by, in this case, a value provided by the lambda function.

CodePudding user response:

How about put the list in the form of dict, with the key as the numeric value extracted from the string, and the value as the string?

Then, you could sort the dict in terms of the key?

CodePudding user response:

You need to pass in a key to sort them on that splits the string and parses the number as a number to sort, you can also then sort alphabetically if you wish for those with the same number.

sorted(num, key=lambda x: (int(x.split()[2]), x))

or

num.sort(key=lambda x: (int(x.split()[2]), x))

CodePudding user response:

You need to use key= to let sort know which value you want to assign each element for sorting.

If the strings are always that structured, you can use:

num = ['ryan has 8 apples','charles has 16 bananas','mylah has 3 watermelons']
num.sort(key=lambda x: int(x.split(' ')[2]))
print(num)

If they are more complex, take a look at regular expressions.

  • Related