Home > Enterprise >  Sorting a two dimensional string list python
Sorting a two dimensional string list python

Time:10-07

I am trying to sort by the second element in a two dimensional list, where all the elements are strings. It seems one of the problems with my current sorting method is that it cannot sort string elements. How would I go about changing it to integer? If possible, I would also like to have the first element correlated to the highest second element printed out. '2001' in this instance.

sqrm_price= [['1999', '7951'], ['2000', '8868'], ['2001', '12502']] 


def highPrice(sqrm_price):
    sort_price = sorted(sqrm_price, key = lambda x: x[1], reverse=True)
    print("The year "   sqrm_price[-1]   " has the highest price with "   sort_price[0]   "$")      
        
highPrice(sqrm_price) 

My preferred output would be " The year 2001 has the highest price with 12502$"

Any help would be greatly appreciated!

CodePudding user response:

You can convert the string to an integer inside your lambda using int(). Also, why sort when you can max?

def highest_price(data):
    year, price = max(data, key=lambda item: int(item[1]))
    print(f"The year {year} has the highest price with ${price}")
# The year 2001 has the highest price with $12502
  • Related