-1

I would appreciate some help with a python piece of code im having issues with.

I have a list which contains strings. Here is a snippet of the list. It is a lot longer though.

[['AAPL', '1d', '58.82', '155.04'], ['MSFT', '1d', '63.16', '118.6']] 

What i am trying to do is to sort the list at index 3 (so the values '155.04' , '118.6' etc). I have tried the following, which doesn't work since i have floats as string i presume.

sorted(list, key=itemgetter(3), reverse=True) 

I've looked into using sort() and sorted() but i cant seem to find a way to both sort ints as strings and also at a particular index.There are no error messages, its just not in the correct order.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69

2 Answers2

1

You can use a lambda to convert to float just for the comparison

values = [['AAPL', '1d', '58.82', '155.04'], ['MSFT', '1d', '63.16', '118.6']]
values = sorted(values, key=lambda x:float(x[3]), reverse=True)
# values stays the same the data is already reverse sorted by the 4th value
azro
  • 53,056
  • 7
  • 34
  • 70
0

Your sort-key has to convert the last element of each sublist to a float.

>>> sorted(lst, key=lambda sublist: float(sublist[-1]), reverse=True)
[['AAPL', '1d', '58.82', '155.04'], ['MSFT', '1d', '63.16', '118.6']]

You could write that lambda function as a non-anonymous function for readability

def last_as_float(lst):
    return float(lst[-1])

and then pass key=last_as_float.

timgeb
  • 76,762
  • 20
  • 123
  • 145