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?