开发者

python sort list of lists with casting

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))
  • I also tried to define my own compare function:

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 .


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜