-1

For example: The names and numbers are in a file.txt that looks like this:

Sara 2,873
Mina 152,167
Josh 100,81
Bo  1,13
Leon 12,4

To read the file into list of lists i used the code:

file_name = open("file.txt", "r")
list_of_lists = []
for line in file_name:
    strip_line = line.strip()                
    line_list = strip_line.split()          
    list_of_lists.append(line_list)        
file_name.close()
print(list_of_lists)

output:

list_of_lists = [['Sara', '2,873'],['Mina', '152,167'], ['Josh', '100.81'], ['Bo', '1,13'], ['Leon', '12.4']]

I want to sort this list by float numbers. It should look like this:

[['Bo', '1,13'], ['Sara', '2,873'], ['Leon', '12,4'], ['Josh', '100.81'], ['Mina', '152,167']]

I tried this code to sort:

def sort_list():
    list_of_lists.sort(key=lambda x: x[1])        
    print(list_of_lists)
sort_list()

But I get this output which is sorted by the name:

[['Bo', '1,13'], ['Josh', '100.81'], ['Leon', '12.4'], ['Mina', '152,167'], ['Sara', '2,873']]

What is wrong with the code? How do I sort by float numbers?

Jofre
  • 3,718
  • 1
  • 23
  • 31
Sphoebe
  • 1
  • 2
  • Those aren't `float` objects, those **are strings**. Strings are sorted lexicographically, as always. If you want to use `float` objects, you have to create actual `float` objects – juanpa.arrivillaga Mar 29 '21 at 12:03

1 Answers1

1

In order to make this "sort" work, you should make sure that you are using those numbers as numbers (float) when sorting.

def sort_list():
    list_of_lists.sort(key=lambda x: float(x[1]))        
    print(list_of_lists)
sort_list()

First make sure that all those string formatted numbers use "." to separate the decimals.

Edit:

This is how the file.txt should look like:

Sara 2.873
Mina 152.167
Josh 100.81
Bo  1.13
Leon 12.4

And this is how the whole code should look like:

file_name = open("file.txt", "r")
list_of_lists = []
for line in file_name:
    strip_line = line.strip()
    line_list = strip_line.split()
    list_of_lists.append(line_list)
file_name.close()
print(list_of_lists)
def sort_list():
    list_of_lists.sort(key=lambda x: float(x[1]))
    print(list_of_lists)
sort_list()

This should work in python 2 and 3 (tested).

  • I tried adding float to the function put i always get this error: TypeError: float() argument must be a string or a number, not 'list' . How do I fix that? – Sphoebe Mar 29 '21 at 12:55
  • Could you please show me where you added the float() please? – Alvaro Rodriguez Mar 29 '21 at 13:26
  • I tried adding it to: list_of_lists.append(float(line_list)) in the first code, and then to the sort_list function like you did and neither worked, Not sure where to add the float() – Sphoebe Mar 29 '21 at 13:42
  • I edited the answer so you will find there how it should look like. If you do list_of_lists.append(float(line_list)), you are trying to convert a list to a float (not possible). – Alvaro Rodriguez Mar 29 '21 at 15:05