python排序列表与铸造

时间:2021-07-14 14:05:36

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:

所以这是问题设置。我有一个包含字符串的列表列表。一列包含实际表示浮点值的字符串。它也是我想要排序的列。问题是,python似乎忽略条目上的 - (减号)符号。所以一个示例列表:

[[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:

到目前为止我尝试过:

  • casting the second column to float and sorting by that column
  • 将第二列转换为浮动并按该列排序

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 .

[编辑]也已经尝试过Ignacio的建议。我应该提到我必须使用python 2.5。

2 个解决方案

#1


18  

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

#2


2  

Mine works fine, Python 3.1.2:

我的工作正常,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:

和2.6.5:

>>> l=[['', '0.3', ''], ['', '0.1', ''], ['', '-0.2', '']]
>>> sorted(l,key=lambda x:float(x[1]))
[['', '-0.2', ''], ['', '0.1', ''], ['', '0.3', '']]

#1


18  

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

#2


2  

Mine works fine, Python 3.1.2:

我的工作正常,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:

和2.6.5:

>>> l=[['', '0.3', ''], ['', '0.1', ''], ['', '-0.2', '']]
>>> sorted(l,key=lambda x:float(x[1]))
[['', '-0.2', ''], ['', '0.1', ''], ['', '0.3', '']]