sorting - python sort list of lists with casting -
i know tat similar questions has been asked several times. , how use search function, still not work.
so here problem setup. have list of lists containing strings. 1 column contains strings represent float values. , column want sort by. problem is, python seems ignore - (minus) sign on entries. example list of:
[[blaa, '0.3', bli], [bla, '0.1', blub], [bla, '-0.2', blub]]
gets sorted this:
[[bla, '0.1', blub], [bla, '-0.2', blub], [blaa, '0.3', bli]]
and not how should be:
[[bla, '-0.2', blub],[bla, '0.1', blub], [blaa, '0.3', bli]]
so far have tried:
- casting second column float , sorting column
like:
for in mylist: i[1] = float(i[1]) mylist.sort(key=lambda x: x[1])
or with
for in mylist: i[1] = float(i[1]) mylist.sort(key=operator.itemgetter(1))
- i tried define own compare function:
like:
mylist.sort(cmp=lambda x,y: cmp(float(x), float(y)), key=operator.itemgetter(1))
and other combination of above methods, same sorted
. far no success, minus sign gets ignored every time. how solve this?
[edit] tried ignacio suggestion. should mention have use python 2.5 .
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']]
Comments
Post a Comment