pythonlistexponent

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


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.


Solution

  • 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.