简体   繁体   中英

How to numerically sort string in list

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM