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?

3
  • possible duplicate of How to sort a list of lists by a specific index of the inner list? Commented Apr 1, 2014 at 8:08
  • list is a python type, using it as a variable name will override current type. Commented Apr 1, 2014 at 8:13
  • Okay, I think I got it to work...apparently all that I needed to do was my_List.sort() ? Commented Apr 1, 2014 at 8:22

3 Answers 3

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.
Sign up to request clarification or add additional context in comments.

Comments

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']]

6 Comments

I get 'could not convert string to float:' error message
builtins.ValueError: could not convert string to float:
@jenncar That means one of the items in your list cannot be converted to float. What exactly does your list contain?
I just realized some of the inner lists have an empty string in position [0]
Sorry, I should have caught this earlier.
|
-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']]

2 Comments

You are comparing strings not float.
list is a python type, using it as a variable name will override current type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.