Skip to content Skip to sidebar Skip to footer

Sorting A List Of Two Element Tuples Numerically And Alphabetically

I have an assignment in which I must create a list of tuples from a string. I do this by splitting the string with .split(). I then iterate over the list and add the items and the

Solution 1:

Another way to reverse a numeric sort is to make the numbers negative in the key function

Now combining with the second sort order into a tuple

count_list.sort(key=lambda x: (-x[1], x[0]))

It's necessary to get rid of the reverse=True, as otherwise the alphabetical sort will be reversed.

Solution 2:

count_list.sort(key=lambda x: int(x[1]), reverse=True)

lamba handles numerical strings in alphabetical order (18 comes before 1503 in reverse) but handles integers in proper numerical order, so converting x[1] to an integer does what you're asking for.

Post a Comment for "Sorting A List Of Two Element Tuples Numerically And Alphabetically"