0

I have a list inside of a list, and the inner list has strings of numbers (float) and words. What I need to sort the list by, is in position list[0]. So for example,

list = [['8.34', 'a'],['3.55', 'c'],['5.92', 'b']]

I'm trying to sort the list numerically to look like

list = [['3.55', 'c'],['5.92', 'b'],['8.34', 'a']] 

I've tried

sorted(list, key = float)

but I get an error message: 'float() argument must be a string or a number' and I've tried using lambda as well. Neither works. Could someone help please?

Bach
  • 6,145
  • 7
  • 36
  • 61
jenncar
  • 5
  • 1
  • 3
  • possible duplicate of [How to sort a list of lists by a specific index of the inner list?](http://stackoverflow.com/questions/4174941/how-to-sort-a-list-of-lists-by-a-specific-index-of-the-inner-list) – Mp0int Apr 01 '14 at 08:08
  • `list` is a python type, using it as a variable name will override current type. – Mp0int Apr 01 '14 at 08:13
  • Okay, I think I got it to work...apparently all that I needed to do was my_List.sort() ? – jenncar Apr 01 '14 at 08:22

3 Answers3

3

You can try passing a lambda function.:

sorted(my_list, key = lambda x : float(x[0]))

x will be an element of the list (which is also a list, because my_list is a list of lists), and float(x[0]) will return the float representation of the first element of that list.

Demo:

>>> my_list = [['8.34', 'a'],['3.55', 'c'],['5.92', 'b']]
>>> print sorted(my_list, key = lambda x : float(x[0]))
[['3.55', 'c'], ['5.92', 'b'], ['8.34', 'a']]

Note:

  • Don't use list as the name of a variable, because you will hide its built-in implementation.
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
2

Your list contains lists, so you cannot use float directly. You need to use a function that returns float value of the first item in each list.

>>> lis = [['8.34', 'a'],['3.55', 'c'],['5.92', 'b']]
>>> lis.sort(key=lambda x: float(x[0]))
>>> lis
[['3.55', 'c'], ['5.92', 'b'], ['8.34', 'a']]
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
-2

This earlier answer can be used in your case also: How to sort a list of lists by a specific index of the inner list?

from operator import itemgetter
list = [['8.34', 'a'],['3.55', 'c'],['5.92', 'b']]
print sorted(list, key=itemgetter(0))

gives the desired output:

[['3.55', 'c'], ['5.92', 'b'], ['8.34', 'a']]
Community
  • 1
  • 1
heidivikki
  • 22
  • 4