How to sort this list to make the exponent value go first?

Question:

Given list = [10, '3 ^ 2', '2 ^ 3'], how to sort the list to make the exponents values ( '3 ^ 2' and 2 ^ 3 ) are before any integer / float value and exponent values are sorted from the base.

Desired Output: ['2 ^ 3', '3 ^ 2', 10]

I have tried to remove() and insert() the value but I can’t figure out how to find the index to insert the value in.

Asked By: TaranJS

||

Answers:

You shouldn’t use list as a variable, it is reserved in python.

Not pretty, but you can use this

sorted(mylist, key=lambda x: (-len(str(x).split('^')), str(x).split('^')[0]))

This is sorting according to two criteria, first if there is an exponent, and then by the value of the base.

Answered By: SergioGM
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.