I know tat similar questions has been asked already several times. And i do now how to use the search function, but it still does not work.
So here is the problem setup. I have a list of lists containing strings. One column contains strings which actually represent float values. And it is also the column i want to sort by. The problem is, that python seems to ignore the - (minus) sign on entries. So an example list of:
[[blaa, '0.3', bli], [bla, '0.1', blub], [bla, '-0.2', blub]]
gets sorted like this:
[[bla, '0.1', blub], [bla, '-0.2', blub], [blaa, '0.3', bli]]
and not how it should be:
[[bla, '-0.2', blub],[bla, '0.1', blub], [blaa, '0.3', bli]]
So far i have tried:
like:
for i in mylist:
i[1] = float(i[1])
mylist.sort(key=lambda x: x[1])
or with
for i in mylist:
i[1] = float(i[1])
mylist.sort(key=operator.itemgetter(1))
like:
mylist.sort(cmp=lambda x,y: cmp(float(x), float(y)), key=operator.itemgetter(1))
And any other combination of the above methods, also the same with sorted
. So far with no success, the minus sign gets ignored every time. How do is solve this?
[edit] Also already tried the Ignacio suggestion. I should mention i HAVE to use python 2.5 .
Use the sort() Function to Sort a List of Lists in Python. The sort() method sorts the list of lists in Python according to the first element of each inner list. This method makes changes in the original list itself. We use the reverse parameter to sort in descending order.
There will be three distinct ways to sort the nested lists. The first is to use Bubble Sort, the second is to use the sort() method, and the third is to use the sorted() method.
Method 1: Sort list of lists using sort() + lambda. The anonymous nature of Python Lambda Functions indicates that they lack a name. The Python sort() can be used to perform this variation of sort by passing a function. The list can be sorted using the sort function both ascendingly and descendingly.
l = [["blaa", "0.3", "bli"], ["bla", "0.1", "blub"], ["bla", "-0.2", "blub"]]
l.sort(key=lambda x: float(x[1]))
>>> [['bla', '-0.2', 'blub'], ['bla', '0.1', 'blub'], ['blaa', '0.3', 'bli']]
Mine works fine, Python 3.1.2:
>>> l=[['', '0.3', ''], ['', '0.1', ''], ['', '-0.2', '']]
>>> sorted(l,key=lambda x:float(x[1]))
[['', '-0.2', ''], ['', '0.1', ''], ['', '0.3', '']]
and 2.6.5:
>>> l=[['', '0.3', ''], ['', '0.1', ''], ['', '-0.2', '']]
>>> sorted(l,key=lambda x:float(x[1]))
[['', '-0.2', ''], ['', '0.1', ''], ['', '0.3', '']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With